problem

After participating in a multi-person project, you will always encounter the following problems.

  • If you need to connect with another person, you need to change the proxy's target to his ip address, and you have to restart the project after you finish the change.
  • Someone submitted the code of the configuration file, overwriting my target configuration. You have to change it back and restart the project again.

It is possible that the code of the configuration file is like this

module.exports = {
  devServer:{
    proxy:{
        '/api':{
            // 一大堆注释掉的target
            target:'<url>', // xx
            // target:'<url>', // 张三
            // target:'<url>', // 李四
        }
    }
  }
}

solve

After spending some time, reading some documents, changing some codes, the project no longer needs to be restarted because of changing the proxy.

Because http-proxy-middleware itself supports dynamic proxy, which is the parameter router

changelog look at 061c732039ffda, support v0.16.0

Then it depends on how to design it.

output

Today I specifically wrote this as a tool nice-proxy to facilitate integration in the project.
Here is a brief introduction to how to use it.

Install

yarn add nice-proxy -D

use

The first step, initialization

npx nice-proxy init

This command will generate a nice-proxy folder in the project root directory, which contains two files.

  • proxy-list.json This file is used to store all your agents.
  • proxy-config.json This file is used to store the proxy you are currently using.
Be sure not to submit the proxy-config.json file to [git][svn]

The second step is to modify the configuration file code

vue-cli

If you are using vue-cli project created, then your vue.config.js so to write file.

const { useNiceProxy } = require("nice-proxy");

module.exports = {
  devServer: {
    proxy: {
      "/api": {
        target: "<url>",
        ws: true,
        changeOrigin: true,
        // 参考vue-cli官网配置示例,只需要添加下面这行参数。
        router: useNiceProxy,
      },
    },
  },
};

webpack

Same as above

Provided command

nice-proxy also provides several commonly used commands to facilitate you to maintain the proxy list.

All commands are effective immediately.

list lists all agents

image.png

add Add agent

image.png

change switch agent

Choose an agent
image.png
Switch successfully
image.png


我是好人
2.2k 声望17 粉丝

Erpack 二次封装ant-design-vue,可以看看。