vue/cli?配置動態(tài)代理無需重啟服務的操作方法
vue腳手架指的是vue-cli,它是一個專門為單頁面應用快速搭建繁雜的腳手架,它可以輕松的創(chuàng)建新的應用程序而且可用于自動生成vue和webpack的項目模板。
vue/cli 配置動態(tài)代理,無需重啟服務
devServe = http://localhost:3000; prodServe = http://localhost:4000;
1. 在vue.config.js文件中,配置代理服務
使用vue/cli@5創(chuàng)建的項目,默認會創(chuàng)建vue.config.js文件,如果項目中沒有此文件,那么就手動在項目根路徑創(chuàng)建vue.config.js文件。
const { defineConfig } = require('@vue/cli-service');
const createProxy = require('./dynamic_proxy');
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'/': {
target: '',
ws: false,
changeOrigin: true,
router: () => {
return createProxy();
}
}
}
}
});2. 在項目根路徑創(chuàng)建文件夾dynamic_proxy,并創(chuàng)建proxy.list.json文件以及index.js文件。
proxy.list.json
[
{
"name": "devServe",
"ip": "http://xxx.xxx.xxx.xxx:3001",
"active": true
},
{
"name": "prodServe",
"ip": "http://xxx.xxx.xxx.xxx:3000",
"active": false
}
]index.js
const { readFileSync } = require('fs');
const { resolve } = require('path');
const getProxyList = () => {
try {
const proxyList = readFileSync(resolve(__dirname, './proxy.list.json'), 'utf-8');
return JSON.parse(proxyList);
} catch (error) {
throw new Error(error);
}
};
const getActiveProxy = () => {
try {
const proxyList = getProxyList();
if (proxyList.some(i => i.active)) {
return proxyList.find(i => i.active);
}
} catch (error) {
throw new Error(error);
}
};
module.exports = () => {
return getActiveProxy().ip;
};3. 運行命令
npm run serve
4. 需要切換服務時,直接修改proxy.list.json中的active選項,修改為true,就可以自動切換了
5. 原理解析
vue cli 的代理是使用的http-proxy-middleware包,所以proxy選項的配置也是基于這個包的配置。在proxy配置選項中有兩個屬性target以及router。其中target是默認的代理地址。而router可以return一個字符串服務地址,那么當兩個選項都配置了時,http-proxy-middleware在解析配置時,會首先使用router函數(shù)的返回值,當router的返回值不可以用時,那么就會fallback至target。
http-proxy-middleware router配置源碼

配置校驗源碼

可以由上面源碼看出首先會校驗配置,如果target和router都不存在的話,就會直接Error,從第一張圖片源碼可以看出,如果router存在的話,則會直接新建一個newTarget,并且將options.target賦值為newTarget;
到此這篇關于vue/cli 配置動態(tài)代理,無需重啟服務的文章就介紹到這了,更多相關vue cli 配置動態(tài)代理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Element?UI中v-infinite-scroll無限滾動組件使用詳解
在移動端數(shù)據(jù)的更新中許多方法孕育而生,無限滾輪也是解決的方案一種,Element-ui為vue開發(fā)了一個事件(v-infinite-scroll),下面這篇文章主要給大家介紹了關于Element?UI中v-infinite-scroll無限滾動組件使用的相關資料,需要的朋友可以參考下2023-02-02
Vue.js+HighCharts實現(xiàn)動態(tài)請求展示時序數(shù)據(jù)
這篇文章主要為大家詳細介紹了Vue.js+HighCharts實現(xiàn)動態(tài)請求展示時序數(shù)據(jù),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03

