![](/img/trans.png)
[英]Vue.js : Best way to implement MPA(Multi page app) in laravel
[英]What is the best way to define multiple configs in a multi-build Vue js app?
我正在開發一個 Vue 3 Web 應用程序,該應用程序將為多個客戶構建和部署。 每個客戶都有自己的標題、標志、圖標等。
我需要的是為每個客戶構建具有特定信息的應用程序(假設在TheFooter.vue
組件中顯示客戶信息)。
重要的要求是,當要為客戶構建應用程序時,出於隱私原因,其他客戶的信息不得包含在最終構建的文件中(我的意思是運行npm run build
后的/dist
文件夾)。
我嘗試的方法:
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 管道)
這個問題有什么想法或最佳實踐嗎?
提前致謝!
生成多個構建基本上是一個兩步過程。
編寫一個自定義構建腳本,以編程方式調用 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
};
};
使用 Webpack DefinePlugin
或其他一些方法將此數據注入到您的實際 JavaScript 代碼中。 對於 HTML 頁面,您可以使用webpack-html-plugin
,它也可以使用模板支持此功能。 您將需要它來為您的客戶構建設置<title>
和其他 HTML 元數據。
new webpack.DefinePlugin({
CUSTOMER_DATA: JSON.stringify(customer)
});
此外,應優化此構建腳本以處理async
,並確保為每個客戶適當調整輸出目錄。
作為額外的增強,Webpack 還支持用於創建多個構建的數組配置( 多個配置)。 您可以使用它,因為它提供了開箱即用的並行構建,而無需單獨的build.js
文件。 我個人喜歡將事情分開/模塊化,因此以這種方式解釋。
這里要理解的關鍵是,在你的實際代碼中,你不應該在任何地方導入這個customers.js
文件。 這是一個構建時的東西,應該只在構建時腳本中導入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.