前不久項目打包交付測試進行測試時,需要打包到不同的測試服務器分別指向其對應api地址,如果打包一次修改一次api地址,那豈不是很麻煩?
今天我們就來解決這個問題:
核心思路:打包輸出一份配置,代碼中獲取配置
方法一:
1.在static(webpack不會編譯)下創建serve.config.js
/**
* @description 打包後抽取的配置 BaseUrl 必須是host地址 + 端口號
*/
(function () {
let win = typeof window == 'undefined' ? global : window
win.Glob = {
BASE_URL: '172.16.0.223/api'
}
})()
注意:如果遇到 window is not defined 因爲在node環境中是global對象
2.在需要用到的地方
// window.Glob.BASE_URL
let host = ''
// 開發環境 npm run dev
if (process.env.NODE_ENV !== 'production') {
host = '/api'
} else {
// 測試環境 npm run test
if (process.env.type == 'test'){
host = 'http://' + window.Glob.BASE_URL
}else { // 正式環境 npm run build
host = 'http://1.1.1.1'
}
}
3.最後在index.html引入
4.打包後效果
方法二:
利用webpack打包出配置文件
1.下載
npm i compression-webpack-plugin -S
2.webpack 3.6 新增插件 generate-asset-webpack-plugin
const GenerateAssetPlugin = require('generate-asset-webpack-plugin')
const createJson = function () {
let serveConfigJson = {
code:200,
data:{
BASE_URL: "172.16.0.94:80"
},
msg:''
}
return JSON.stringify(serveConfigJson,null,4)
}
// 3.6利用webpack.plugin.push 添加插件 --- 4.0 :Compiler.hooks.xxx.tap(<plugin name>, fn)
webpackConfig.plugins.push(
// 抽離打包配置文件
new GenerateAssetPlugin({
filename: 'serve.config.json', // 輸出到test根目錄下的serve.config.json
fn: (compilation, cb) => {
cb(null, createJson(compilation))
},
extraFiles: []
})
)
3.main.js中vue.prototype賦值
request.get('./serve.config.json')
.then(res => {
Vue.prototype.BASE_URL = res.data.baseURI
})
.catch(err => {
throw 'serve.config.json is not defined'
})
4.打包後效果