Skip to content

Library Mode: Able to conditional set options based on the format that is used. #7617

@ericfennis

Description

@ericfennis

Clear and concise description of the problem

As a developer using Vite I want to able to conditional set vite configurations based on the used library mode format.
Currently this is not possible.

Suggested solution

I thought of something like this, but I'm not sure if this possible because the current env parameter is set with properties before the viteconfig is being created. So it will maybe impossible to know the formats.

import path from "path";
import { defineConfig } from "vite";

export default defineConfig((env) => ({
  build: {
    lib: {
      entry: path.resolve(process.cwd(), 'lib/main.ts'),
      name: 'MyLib',
      formats: ['umd', 'cjs', 'es'],
      fileName: (format) => `${format}/my-lib.js`
    },
    rollupOptions: {
      output: {
        preserveModules: env.libFormat === 'es'
      }
    }
  },
}))

Alternative

Alternatively I thought of something like this. By this you can configure multiple configs for each format. This maybe easier to adapt but can be less readable.

import path from "path";
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    lib: {
      entry: path.resolve(process.cwd(), 'lib/main.ts'),
      name: 'MyLib',
      formats: ['umd', 'cjs', 'es'],
      fileName: (format) => `${format}/my-lib.js`,

      // Build config only for "LibraryMode"
      buildConfig: {
        minify: false
      },

      // or: Conditional config for each format
      buildConfig: (format) => ({
        rollupOptions: {
          output: {
            preserveModules: format === 'es'
          }
        }
      })
    },
  },
})

Additional context

Maybe duplicate of #6954

Validations

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions