一,命令
npm run build -環(huán)境 -域名 -打包文件夾 -平臺(tái)
npm run serve -prod -http://xx.com -dist -0
npm run build -prod -http://xx.com -dist -0
二,參數(shù)說明:
1,環(huán)境,測試 uat 跟 正式 prod,必填:如果不指定需要填寫 0
2,域名,需要打包或者運(yùn)行的命令,必填:如果不指定需要填寫 0 默認(rèn)取config配置域名
3,打包文件夾,必填:如果不指定需要填寫 0 默認(rèn)是dist
4,平臺(tái),可選,需要打包打包的平臺(tái),一套代碼不輸給不同用戶,涉及到的logo,favicon.ico不一致,需要做專門配置
參數(shù)可自行定義,
三,原理
通過獲取命令行參數(shù),將命令行參數(shù)解析成對應(yīng)字段內(nèi)容,通過webpack傳入到頁面,供網(wǎng)絡(luò)請求等使用。
四,代碼說明
在項(xiàng)目根目錄新建config 文件夾
添加environment.js跟index.js文件
environment.js 文件內(nèi)容 -- 解析命令行參數(shù)
const configArgv = JSON.parse(process.env.npm_config_argv);
const original = configArgv.original.slice(1);
const stage = original[1] ? original[1].replace(/-/g, "") : "uat";
const requestHttp = original[2] ? original[2].replace(/-/g, "") : "0";
const distName = original[3] ? original[3].replace(/-/g, "") : "0";
const platform = original[4] ? original[4].replace(/-/g, "") : "0";
module.exports = {
? ? stage,
? ? requestHttp,
? ? platform,
? ? distName
};
index.js 文件內(nèi)容 -- 配置各環(huán)境默認(rèn)域名
const config = {
? ? uat: { // 測試環(huán)境網(wǎng)絡(luò)請求地址
? ? ? ? "0": "http://xx.com"
? ? },
? ? prod: { // 正式環(huán)境網(wǎng)絡(luò)請求地址
? ? ? ? "0": "http://xx.com"
? ? }
}
module.exports = {
? ? config
};
vue.config.js配置
const environment = require("./config/environment"); // 引入獲取命令行參數(shù)js
const baseconfig = require("./config").config;
if (environment.requestHttp == '0') {
? ? environment.requestHttp = process.env.NODE_ENV === 'production' ? baseconfig.prod[environment.platform] : baseconfig.uat[environment.platform];
}
module.exports = {
? ? ...
? ? ?chainWebpack: config => {
????????????config.plugin("define").tap(args => {? ? ? ? // 講參數(shù)傳入項(xiàng)目中,可在main.js或者項(xiàng)目中的config? 通過process.env 獲取
? ? ? ? ? ? ????args[0]["process.env"].STAGE = JSON.stringify(environment.stage);
? ? ? ? ? ? ????args[0]["process.env"].URL = JSON.stringify(environment.requestHttp)
? ? ? ? ? ????? args[0]["process.env"].PLATFORM = JSON.stringify(environment.platform);
? ? ? ? ? ? ????return args;
? ? ? ? ????});
? ? ? ? ? ? ...
?????} ,
????devServer: {
? ? ? ? ...
? ? ? ? proxy: environment.requestHttp || null, // 配置代理
? ? ? ? ...
? ? ? },
? ? ...
}
五,使用
在main.js或者配置域名的地方使用,
console.log(process.env);