'How to set multiple output when build lib with vite

When I try to build a lib in vue3, I want to set multiple output file. Code like this:

rollupOptions {
  output: [
    {
      file: 'bundle.js',
      format: 'cjs'
    },
    {
      file: 'bundle.min.js',
      format: 'iife',
      name: 'version',
    }
  ]
}

Then I will get an error:

You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks"

So, how should I do can make this work?

vite: 2.3.7



Solution 1:[1]

I guess your looking for https://vitejs.dev/guide/build.html#library-mode

And see https://vitejs.dev/config/#build-lib to tweak your needs.

Solution 2:[2]

? You are missing the input config in rollupOptions.

The following config will generate a my-app.js in a dir myoutput (you may need to adjust file path according to your setup) :

    rollupOptions: {
      input: {
        app: 'bundle.js',
      },
      output: {
        entryFileNames: 'my-[name].js',
        dir: './myoutput'
      }
    }

result illustration

? To understand this answer better, please read the following sentence :

If you provide an array of entry points or an object mapping names to entry points, they will be bundled to separate output chunks.

And unless the output.file option is used, generated chunk names will follow the output.entryFileNames option. When using the object form, the [name] portion of the file name will be the name of the object property while for the array form, it will be the file name of the entry point.

Note that it is possible when using the object form to put entry points into different sub-folders by adding a / to the name.

If we follow the doc we can get more precisions and we know that :

output.dir
Type: string
Set in build.rollupOptions

Is for: The directory in which all generated chunks are placed and this option is required if more than one chunk is generated. Otherwise, the file option can be used instead.

output.file
Type: string

The file to write to. Can only be used if not more than one chunk is generated.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yooouuri
Solution 2