在和后端对接接口的过程中,手动修改环境配置时,一般需要手动重启编译才能应用新的前端服务器代理选项,频繁切换或者重启编译很耗时的时候是非常影响开发体验的。
其实根据webpack-dev-server所使用的http代理插件,可以轻松实现动态配置。
思路
- 获取可以动态修改proxy的属性
-
webpack-dev-server
- 内部使用的插件为http-proxy-middleware,
- 可以用来修改配置的参数为
router(object/function)
-
- 监听配置文件变化。使用
chokidar - 重新配置proxy
实现
- 安装chokidar
npm install -D chokidar - 把代理切换配置整理成文件,假设为config.js
const proxy = { dev: { 'api': 'http://127.0.0.1:8999', }, prod: { 'api': 'http://127.0.0.1:9999', }, }; exports.config = proxy['dev']; - 监听文件变化,修改配置
现在修改config.js的内容,就能切换代理了,无需重启编译const chokidar = require('chokidar'); const path = require('path'); const configPath = path.resolve(__dirname, './config.js') const config = require(configPath); chokidar.watch(configPath).on('change', () => { // 删除模块的缓存,确保获取的值是新的 delete require.cache[require.resolve(configPath)]; const newConfig = require(configPath); Object.assign(config, newConfig); }); /** * @type {import('webpack-dev-server').Configuration} */ export const devServerConfig = { host: '0.0.0.0', // 其他配置 proxy: { '^/api': { target: config.api, changeOrigin: true, router: () => config.api, }, } }