webpack配置动态代理无需重启服务的方法

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

//增加此方法
const hotRequire = modulePath => {
  // require.resolve可以通过相对路径获取绝对路径
  // 以绝对路径为键值删除require中的对应文件的缓存
  delete require.cache[require.resolve(modulePath)]
  // 重新获取文件内容
  const target = require(modulePath)
  return target
}

...
devServer: {
    open: true,
    host: '0.0.0.0',
    port: 8081,
    hot: true,
    proxy: {
      '/abc': {
        target:"http://xxxx.com/",
        secure: false, //false为http访问,
        changeOrigin: true,    
        router: () => {   //添加router配置
          return hotRequire('./target');
        }
      },
    }

2、创建文件target.js

const target = [
  'http://xxx.com/',
  'http://xxx123.com/',
][0]

module.exports = target

4、运行

输入命令npm run serve

要更改代理时,修改target.js文件,并刷新页面即可

原理点此链接
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。