我正在開發一個 Vue 3 Web 應用程式,該應用程式將為多個客戶構建和部署。每個客戶都有自己的標題、徽標、圖示等
。我需要的是為每個客戶構建具有特定資訊的應用程式(假設在TheFooter.vue組件中顯示客戶資訊)。
重要的要求是,當要為客戶構建應用程式時,出于隱私原因,其他客戶的資訊不得包含在最終構建的檔案中(我的意思是/dist運行后的檔案夾npm run build)。
我嘗試的方法:
- 創建一個 customers.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
但通過這種方式,我分析了/dist檔案夾中最終構建的 js ,其他客戶的資訊可用。
基于Vue CLI模式,為每個客戶創建一個
.env.customer_x檔案并在其中添加客戶特定的資料,然后在構建應用程式時使用--mode標志(例如vue-cli-service build --mode customer_x)參考當前客戶。如果客戶太多,我們最終會得到太多的 .env.customer_... 檔案。(此解決方案還有其他注意事項嗎?)創建一個json檔案(例如customers.json)并
TheFooter.vue像這樣使用它:
import { process.env.VUE_APP_CURRENT_CUSTOMER } from './customers.json'
但似乎不可能在import陳述句中使用變數,我需要使用env變數(用于ci/cd管道)
這個問題有什么想法或最佳實踐嗎?
提前致謝!
uj5u.com熱心網友回復:
生成多個構建基本上是一個兩步程序。
第 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
};
};
第二步:資料注入
使用 WebpackDefinePlugin或其他一些方法將這些資料注入到您的實際 JavaScript 代碼中。對于 HTML 頁面,您可以使用webpack-html-plugin,也可以使用模板來支持此功能。您將需要它來<title>為客戶的構建設定和其他 HTML 元資料。
new webpack.DefinePlugin({
CUSTOMER_DATA: JSON.stringify(customer)
});
此外,應優化此構建腳本以處理async并確保為每個客戶適當調整輸出目錄。
作為額外的增強,Webpack 還支持用于創建多個構建的陣列配置(多個配置)。您可以使用它,因為它提供了開箱即用的并行構建,而無需單獨的build.js檔案。我個人喜歡將事物分開/模塊化,因此以這種方式解釋。
這里要理解的關鍵是,在你的實際代碼中,你不應該在任何地方匯入這個customers.js檔案。這是一個構建時的東西,應該只在構建時腳本中匯入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329302.html
標籤:javascript Vue.js 网络包 Vuejs3 vue-cli
