在webpack-dev-server中动态修改proxy配置,无需重启编译

357 阅读1分钟

在和后端对接接口的过程中,手动修改环境配置时,一般需要手动重启编译才能应用新的前端服务器代理选项,频繁切换或者重启编译很耗时的时候是非常影响开发体验的。

其实根据webpack-dev-server所使用的http代理插件,可以轻松实现动态配置。

思路

  1. 获取可以动态修改proxy的属性
  2. 监听配置文件变化。使用chokidar
  3. 重新配置proxy

实现

  1. 安装chokidar
    npm install -D chokidar
    
  2. 把代理切换配置整理成文件,假设为config.js
    const proxy = {
        dev: {
            'api': 'http://127.0.0.1:8999',
        },
        prod: {
            'api': 'http://127.0.0.1:9999',
        },
    };
    exports.config = proxy['dev'];
    
  3. 监听文件变化,修改配置
    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,
            },
        }
    }
    
    现在修改config.js的内容,就能切换代理了,无需重启编译