webpack如何配置多个public静态目录实现Vue项目多客户定制构建?
实现方案
核心思路是修改Vue CLI内置的copy-webpack-plugin拷贝规则,利用插件按顺序拷贝、后拷文件覆盖前拷同名文件的特性,实现通用静态资源和客户专属静态资源的合并与优先级控制,同时配套修改开发服务器配置适配本地开发场景。
完整vue.config.js配置如下:
const path = require('path') // 读取命令行传入的customer参数 const customer = process.env.npm_config_customer if (!customer) { throw new Error('请指定客户参数,示例:npm run build --customer=customer1') } // 拼接对应客户的public目录绝对路径 const customerPublicPath = path.resolve(__dirname, `src/${customer}/public`) module.exports = { chainWebpack: config => { // 修改内置的copy-webpack-plugin配置 config.plugin('copy').tap(options => { // 追加客户专属public目录的拷贝规则,放在默认规则之后 options[0].push({ from: customerPublicPath, to: path.resolve(__dirname, 'dist'), toType: 'dir', noErrorOnMissing: true, // 客户public目录不存在时不报错 globOptions: { ignore: ['.DS_Store'] // 忽略系统冗余文件 } }) return options }) }, // 开发环境静态资源配置,Vue CLI 5+版本使用以下配置 devServer: { static: { directory: customerPublicPath, watch: true // 监听客户public目录文件变化,自动热更新 } } // 如果使用Vue CLI 4及更早版本,替换上面的devServer配置为: /* devServer: { contentBase: customerPublicPath, watchContentBase: true } */ }
使用方法
- 构建对应客户的生产包:执行
npm run build --customer=customer1 - 本地开发对应客户的项目:执行
npm run serve --customer=customer1
配置生效后,构建产物的dist目录会自动合并根目录public和对应客户public下的所有资源,同名文件以客户目录下的为准。
内容的提问来源于stack exchange,提问作者mlst
相关产品推荐
相关产品推荐

