在多构建Vue js应用程序中定义多个配置的最佳方法是什么?



我正在为多个客户构建和部署一个Vue 3 web应用程序。每个客户都有自己的标题,徽标,图标等。
我需要的是为每个客户构建具有其特定信息的应用程序(假设在TheFooter.vue组件中显示客户信息)。
重要的要求是,当应用程序要为客户构建时,其他客户的信息必须不包含在最终构建文件(我的意思是/dist文件夹后运行npm run build)出于隐私原因。

我尝试过的方式:

  1. 创建一个customs .js文件并导出一个对象,像这样:
const customers = {
CUSTOMER_A: {
title: 'Customer A',
logo: 'assets/customer_a_logo.png',
// other privacy related data
},
CUSTOMER_B: {
title: 'Customer B',
logo: 'assets/customer_b_logo.png',
// other privacy related data
}
export default const customer[process.env.VUE_APP_CURRENT_CUSTOMER]

然后在.env文件中,创建一个VUE_APP_CURRENT_CUSTOMER密钥,其值如CUSTOMER_A,CUSTOMER_B,…
并在TheFooter.vue导入客户数据如下:
const customer = require('./customers.js').default
但这样我分析最终构建的js在/dist文件夹和其他客户的信息是可用的。

  1. 基于Vue CLI模式,为每个客户创建一个.env.customer_x文件,并在其中添加客户特定的数据,然后在构建应用程序时引用当前客户的--mode标志(例如vue-cli-service build --mode customer_x)。如果客户太多,我们最终会有太多的客户。文件。(对于这个解决方案还有其他注意事项吗?)

  2. 创建一个json文件(例如客户.json),并使用它在TheFooter.vue像这样:
    import { process.env.VUE_APP_CURRENT_CUSTOMER } from './customers.json'
    但它似乎是不可能使用变量内导入语句,我需要使用环境变量(ci/cd管道)

对于这个问题有什么想法或最佳实践吗?

提前感谢!

生成多个构建基本上是两个步骤的过程。

步骤1:自定义脚本构建编写一个自定义构建脚本,以编程方式调用Webpack。像这样:

// build.js file
const webpack = require('webpack');
// Your webpack.config.js should export a function instead of config.
const webpackConfig = require('./webpack.config.js');
// You can require this data from other `customers.js` file.
const customers = [
{ title: 'App 1' },
{ title: 'App2' }
];
customers.forEach((customer) => {
// Get webpack configuration for this customer.
const config = webpackConfig(customer);
// Invoke the webpack
webpack(config, (err) => {
/** Handle error here */
});
});

你的Webpack配置将被封装在一个回调函数中:

// webpack.config.js
module.exports = (customer) => {
// This function will be called from build.js file.

return {
entry: 'index.js',
output: { 
// ...
}
// ...other webpack configuration
};
};

步骤2:数据注入

使用WebpackDefinePlugin或其他方法将这些数据注入到实际的JavaScript代码中。对于HTML页面,您可以使用webpack-html-plugin,它也可以使用模板支持此功能。您将需要它来为客户的构建设置<title>和其他HTML元数据。

new webpack.DefinePlugin({
CUSTOMER_DATA: JSON.stringify(customer)
});

此外,应该优化此构建脚本以处理async,并确保为每个客户适当调整输出目录。

作为一个额外的增强,Webpack还支持数组配置(多个配置)用于创建多个构建。您可以使用它,因为它提供了开箱即用的并行构建,而不需要单独的build.js文件。我个人喜欢保持事物的分离/模块化,并以此方式进行解释。

这里理解的关键是,在实际代码中,您应该在中没有导入customers.js文件。它是一个构建时的东西,应该只在构建时脚本中导入。