前言
在 Vue 项目中,npm script
里通常用 vue-cli-service build
来构建,该命令默认会使用 vue.config.js
作为配置文件
但如果我想在一个 Vue 项目中使用多个配置文件来构建不同产物的需求,该如何处理呢?
vue-cli-service
并没有设计支持使用类似 --config myConfigFile
这样的参数来指定使用其它配置文件,那么还有其它办法么?
VUE_CLI_SERVICE_CONFIG_PATH
查看 源码 发现,vue-cli-service
是支持使用 VUE_CLI_SERVICE_CONFIG_PATH
环境变量来自定义配置文件:
// vue-cli/packages/@vue/cli-service/lib/Service.js
loadUserOptions () {
let fileConfig, pkgConfig, resolved, resolvedFrom
const configPath = (
process.env.VUE_CLI_SERVICE_CONFIG_PATH ||
path.resolve(this.context, 'vue.config.js')
)
if (fs.existsSync(configPath)) {
try {
fileConfig = require(configPath)
if (typeof fileConfig === 'function') {
fileConfig = fileConfig()
}
if (!fileConfig || typeof fileConfig !== 'object') {
error(
`Error loading ${chalk.bold('vue.config.js')}: should export an object or a function that returns object.`
)
fileConfig = null
}
} catch (e) {
error(`Error loading ${chalk.bold('vue.config.js')}:`)
throw e
}
}
// xxx ...
}
既然可以通过 VUE_CLI_SERVICE_CONFIG_PATH
来指定,那就比较容易解决了。
新建 build.js
脚本:
const { spawnSync } = require("child_process");
const path = require("path");
const buildByConfigFile = async (module) =>
return spawnSync('npm', ['run', 'build'], {
shell: true,
env: {
...process.env,
VUE_CLI_SERVICE_CONFIG_PATH: path.resolve(
__dirname,
`vue.config.${module}.js`
),
},
stdio: 'inherit',
});
};
const build = async () => {
await buildByConfigFile('module1');
await buildByConfigFile('module2');
}
然后新建一个 npm script
内容为: "build:multi": "node build.js"
。
成了。