Vue 新增不參與打包的介面地址組態檔
by:授客 QQ:1033553122
開發環境
Win 10
Vue 2.5.2
問題描述
vue工程專案,npm run build webpack方式打包,每次打包后如果需要更改后臺介面地址(專案中,介面地址設定成變數,存放在js檔案中,需要用到的地方匯入),都需要重新打包,比較麻煩,所以,想給專案增加個組態檔,打包后如果要更改介面地址,修改該檔案即可,
解決方法
創建config.js
專案根目錄/static目錄下,創建config.js檔案,內容如下:
;(function(env) {
// 開發環境介面服務器地址
const dev = {
API_BASE_URL:"http://localhost:8000"
}
// 線上環境介面服務器地址
const prod = {
API_BASE_URL:"http://10.xxx.xx.xx:8001"
}
if (env == "dev") {
return dev
} else if (env == "prod") {
return prod
}
})("dev")
修改main.js
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檔案內容 response.data,然后通過eval(response.data)檔案內容當做代碼執行,進而獲取js中函式回傳的內容,即我們需要的配置,并掛載在Vue的prototype上,就可以在每個 Vue 的實體中使用,這里把vue創建實體放在獲取config.js組態檔之后主要是因為axios異步請求的緣故,
注意,這里不能不能使用import,一定要發起網路請求,去請求這個js檔案,否則build時,webpack會將此組態檔應當輸出的值寫死在壓縮之后的js中,之后去動手修改dist/static中的組態檔就不起作用了,
另外,添加{ headers: { "Cache-Control": "no-cache" } }請求頭,防止瀏覽器從磁盤快取讀取,導致后臺更改了配置,前臺讀取的還是舊的檔案,
npm run build后,config.js位于dist/static目錄下,專案線上環境nginx 靜態檔案路由關鍵配置如下:
location / {
root /opt/TMP/frontend/dist; #這里的dist存放的就是上述打包的路徑
...
實踐表明,使用nginx部署的情況下,myConfigPath 不能設定為 "./static/config.js",只能設定為myConfigPath = "/static/config.js",即配置為絕對路徑,否則重繪某些頁面的情況下,會請求不到config.js
以下為配置myConfigPath 為 "./static/config.js"的情況下,執行二級頁面的重繪操作(頁面URL:http://10.1xx.xx.xx/testerView/testCaseManagement,根據我的專案程式設計,此操作會先訪問二級路由頁面testerView),查看nginx日志,發現如下,請求找不到:
參考配置
本例中,在自己封裝的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
})
...略
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/77922.html
標籤:JavaScript
上一篇:css 隱藏滾動條
