问题描述
在使用 vue-cli3 创建项目时,如果在 vue.config.js 中配置了代理,那么在开发环境下,每次修改代理配置后都需要重启项目才能生效,这样就会造成开发效率的降低,因此需要解决这个问题。
解决方案
根目录下新建proxy.js和proxy-config.js,然后在 vue.config.js 中引入 proxy.js
vue.config.js
const proxy = require('./proxy')
module.exports = {
// 由于浏览器有跨域限制,这里cli 工具提供了 启动本地代理服务器 请求
devServer: {
open: false, // 是否打开浏览器;
hotOnly: true, // 是否热更新;
port: 8012,
proxy: proxy
}
}

image.png
proxy.js
const fs = require('fs')
function looseJsonParse (obj) {
return Function('"use strict";return (' + obj + ')')()
}
let currentProxy = ''
function getUrl (key) {
const router = fs.readFileSync('./proxy-config.js', 'utf8')
const a = router.indexOf('{')
const b = router.lastIndexOf('}')
const proxy = looseJsonParse(router.substring(a, b + 1))
if (currentProxy !== proxy[key]) {
console.log(`${key} proxy changed =>`, proxy[key])
}
currentProxy = proxy[key]
return proxy[key]
}
module.exports = {
'/es/api': {
target: 'target', // 这个字段必须有
router: () => getUrl('esApiUrl'),
changeOrigin: true,
pathRewrite: {
'^/es/api': ''
}
},
'/pra': {
target: 'target',
router: () => getUrl('pra'),
changeOrigin: true,
pathRewrite: {
'^/pra': ''
}
}
}
proxy-config.js
const proxy = {
esApiUrl: 'http://172.16.7.161:9200',
// 后端1环境
// pra: 'http://172.18.13.18:8011/pra',
// 145环境
// pra: 'http://xxx.xx.x.145:9904/pra',
// 测试108环境
// pra: 'http://xxx.xx.x.108:10000/pra'
}
