当我尝试在 vue3 中构建库时,我想设置多个输出文件。代码如下:
rollupOptions {
output: [
{
file: 'bundle.js',
format: 'cjs'
},
{
file: 'bundle.min.js',
format: 'iife',
name: 'version',
}
]
}
然后我会得到一个错误:
您必须为单文件构建设置“output.file”,或者在生成多个块时设置“output.dir””
那么,我该怎么做才能使这项工作成功?
vite:2.3.7
👉 您缺少
input
中的 rollupOptions
配置。
以下完整的vite配置示例将生成一个
index.bundle.[moduleFormat].js
import { defineConfig } from "vite";
// https://vitejs.dev/config/
export default (opts: { mode: "production" | "development"; command: "build" | "serve" }) => {
return defineConfig({
build: {
target: "es2020",
commonjsOptions: {
sourceMap: false
},
rollupOptions: {
input: {
index: "./src/index.js"
},
/* single
output: {
format: "umd",
strict: false,
chunkFileNames: `[name].[hash].js`,
entryFileNames: "[name].bundle.umd.js",
dir: "dist"
},
*/
// array config example
// from rollup: export type InternalModuleFormat = 'amd' | 'cjs' | 'es' | 'iife' | 'system' | 'umd';
output: [
{
format: 'cjs',
entryFileNames: "[name].bundle.[format].js",
},
{
format: 'es',
entryFileNames: "[name].bundle.[format].js",
},
{
format: 'umd',
entryFileNames: "[name].bundle.[format].js",
},
]
}
}
});
};
💡为了更好地理解这个答案,请阅读以下句子:
如果您提供入口点数组或对象映射名称到入口点,它们将被捆绑到单独的输出块。
除非使用
output.file
选项,否则生成的块名称将遵循 output.entryFileNames
选项。当使用对象形式时,文件名的 [name]
部分将是 object property
的名称,而对于数组形式,它将是入口点的文件名。
请注意,使用对象形式时可以通过在名称中添加
/
将入口点放入不同的子文件夹中。
如果我们遵循文档,我们可以获得更高的精度,我们知道:
output.dir
Type: string
Set in build.rollupOptions
用于:放置所有生成的块的目录,如果生成多个块,则需要此选项。否则,可以使用文件选项来代替。
output.file
Type: string
要写入的文件。仅在生成不超过一个块时才能使用。
配置 Vite 页面以根据您的需求进行调整。