Win 10
Vue 2.5.2
vue工程項(xiàng)目,npm run build webpack方式打包,每次打包后如果需要更改后臺接口地址(項(xiàng)目中,接口地址設(shè)置成變量,存放在js文件中,需要用到的地方導(dǎo)入),都需要重新打包,比較麻煩,所以,想給項(xiàng)目增加個(gè)配置文件,打包后如果要更改接口地址,修改該文件即可。
項(xiàng)目根目錄/static目錄下,創(chuàng)建config.js文件,內(nèi)容如下:
;(function(env) {
// 開發(fā)環(huán)境接口服務(wù)器地址
const dev = {
API_BASE_URL:"http://localhost:8000"
}
// 線上環(huán)境接口服務(wù)器地址
const prod = {
API_BASE_URL:"http://10.xxx.xx.xx:8001"
}
if (env == "dev") {
return dev
} else if (env == "prod") {
return prod
}
})("dev")
import axios from "axios"
...略
let myConfigPath = "/static/config.js"
if (process.env.NODE_ENV === "development") {
myConfigPath = "../static/config.js"
}
axios.get(myConfigPath, { headers: { "Cache-Control": "no-cache" } }).then(response => {
Vue.prototype.$apiBaseURL = eval(response.data).API_BASE_URL
new Vue({
el: "#app",
router,
store, // 注入 store
components: { App },
template: "<App/>"
})
})
如上,先通過請求,獲取config.js文件內(nèi)容 response.data,然后通過eval(response.data)文件內(nèi)容當(dāng)做代碼執(zhí)行,進(jìn)而獲取js中函數(shù)返回的內(nèi)容,即我們需要的配置,并掛載在Vue的prototype上,就可以在每個(gè) Vue 的實(shí)例中使用。這里把vue創(chuàng)建實(shí)例放在獲取config.js配置文件之后主要是因?yàn)?/strong>axios異步請求的緣故。
注意,這里不能不能使用import,一定要發(fā)起網(wǎng)絡(luò)請求,去請求這個(gè)js文件,否則build時(shí),webpack會將此配置文件應(yīng)當(dāng)輸出的值寫死在壓縮之后的js中,之后去動手修改dist/static中的配置文件就不起作用了。
另外,添加{ headers: { "Cache-Control": "no-cache" } }請求頭,防止瀏覽器從磁盤緩存讀取,導(dǎo)致后臺更改了配置,前臺讀取的還是舊的文件。
npm run build后,config.js位于dist/static目錄下,項(xiàng)目線上環(huán)境nginx 靜態(tài)文件路由關(guān)鍵配置如下:
location / {
root /opt/TMP/frontend/dist; #這里的dist存放的就是上述打包的路徑
...
實(shí)踐表明,使用nginx部署的情況下,myConfigPath 不能設(shè)置為 "./static/config.js",只能設(shè)置為myConfigPath = "/static/config.js",即配置為絕對路徑,否則刷新某些頁面的情況下,會請求不到config.js
以下為配置myConfigPath 為 "./static/config.js"的情況下,執(zhí)行二級頁面的刷新操作(頁面URL:http://10.1xx.xx.xx/testerView/testCaseManagement,根據(jù)我的項(xiàng)目程序設(shè)計(jì),此操作會先訪問二級路由頁面testerView),查看nginx日志,發(fā)現(xiàn)如下,請求找不到:
本例中,在自己封裝的axios.js中使用該配置
import axios from"axios"
import Vue from "vue"
...略
function request(options) {
return new Promise((resolve, reject) => {
const instance = axios.create({
baseURL: Vue.prototype.$apiBaseURL,
headers:config.headers,
timeout:config.timeout,
withCredentials:config.withCredentials,
responseType:config.responseType
})
...略