vue/cli 配置动态代理,无需重启服务

 devServe = http://localhost:3000;
prodServe = http://localhost:4000;

1. 在vue.config.js文件中,配置代理服务

使用vue/cli@5创建的项目,默认会创建vue.config.js文件,如果项目中没有此文件,那么就手动在项目根路径创建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. 在项目根路径创建文件夹
dynamic_proxy
,并创建
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函数的返回值,当router的返回值不可以用时,那么就会fallback至target。

http-proxy-middleware router配置源码

image

配置校验源码

image

  • 可以由上面源码看出首先会校验配置,如果
    target
    router
    都不存在的话,就会直接Error,从第一张图片源码可以看出,如果router存在的话,则会直接新建一个
    newTarget
    ,并且将
    options.target
    赋值为
    newTarget

标签: Javascript

添加新评论