Vue dynamic agent does not need to restart the project solution

1. Background

When we build the project in vue, we will vue.config.jsconfigure the server address we need to proxy in. Sometimes we need to use different back-end server addresses, that is, the test environment, grayscale environment, formal environment, etc. in our development. At this time, if we need to use different environment addresses, we need to use commands or manually modify them. vue.config.jsConfigured in to restart the project. When the project is getting bigger and bigger, we need a long time to start the project, so repeated, which greatly affects our development progress. At this time, we urgently need a vue动态代理无须重启项目解决方案way to improve our development projects. Based on this background, the following solutions have emerged.

2. Technical solution

2.1 Old configuration scheme

The proxy schemes we vue.config.jscommonly use in China are as follows:

const port = process.env.port || process.env.npm_config_port || 80 // 端口
module.exports = {
    
    
  lintOnSave: false,
  devServer: {
    
    
    host: '0.0.0.0',
    port,
    open: false,
    proxy: {
    
    
      '/my-api': {
    
    
        target: 'https://www.baidu.com',
        ws: false,
        changeOrigin: true,
      }
    }
  }
}

When starting the project, the configuration file will only be read once. When targetthe address is modified again, vue-clithe change of the file cannot be sensed, so the proxy is still the old address, so we need to restart the project to make the configuration take effect. Is there a solution that can make the file change aware when the configuration is modified vue-cli, so as to read the new configuration? The plan is as follows:

2.2 New configuration scheme ideas

vue-cliThe proxy is the package used http-proxy-middleware, so proxythe configuration of the options is also based on the configuration of this package. In proxyconfigure options there are two properties targetas well router. where t argetis the default proxy address. You can return a string service address, then routerwhen both options are configured, the return value http-proxy-middlewarewill be used first when parsing the configuration, router函数and when the return value of router is not available, then it will fallback to target.

http-proxy-middleware router configuration source code
insert image description here

Configuration verification source code
insert image description here

We can use proxyit to routerread our proxy configuration file, so that we can modify the proxy configuration file to update the proxy address without starting the project.

3. Configuration

vue.config.jsAdd the following configuration in :

// vue.config.js
const dynamicProxy = require('./environments/proxy.js')
const port = process.env.port || process.env.npm_config_port || 80 // 端口

module.exports = {
    
    
  lintOnSave: false,
  devServer: {
    
    
    host: '0.0.0.0',
    port,
    open: false,
    proxy: dynamicProxy.proxy,
    disableHostCheck: true
  },
}

Create a new environmentsfolder and create a new proxy.jsfile in it

// proxy.js
const fs = require('fs')
const path = require('path')

const encoding = 'utf-8'
/**
 * 获取配置文件内容 getContent('proxy-config.json')
 * @param filename env.json
 * @returns {string}
 */
const getContent = filename => {
    
    
  const dir = path.resolve(process.cwd(), 'environments')
  return fs.readFileSync(path.resolve(dir, filename), {
    
     encoding })
}

const jsonParse = obj => {
    
    
  return Function('"use strict";return (' + obj + ')')()
}

/**
 * 获取配置选项 getConfig()
 * @returns {
    
    {}|*}
 */
const getConfig = () => {
    
    
  try {
    
    
    return jsonParse(getContent('proxy-config.json'))
  } catch (e) {
    
    
    return {
    
    }
  }
}

module.exports = {
    
    
  proxy: {
    
    
  	// 接口匹配规则自行修改
    ['/my-api']: {
    
    
      target: 'that must have a empty placeholder', // 这里必须要有字符串来进行占位
      changeOrigin: true,
      router: () => (getConfig() || {
    
    }).target || ''
    }
  }
}

proxy.jsFinally, an object is exported, which is very similar to the old proxy scheme we used before, but there is one more router配置, router函数which returns the execution getConfigfunction to read the content of the configuration file, which is our proxy address.

environmentsCreate a new proxy configuration file in the directory proxy-config.json:

{
    
    
    "target": "https://www.baidu.com"
}

When the project starts, our proxy configuration file will be read. After the project starts, we manually modify the proxy address of the proxy configuration file, and then refresh the page to make our new proxy address take effect.

4. Example demo

https://github.com/atdow/vue-dynamic-proxy-demo

Guess you like

Origin blog.csdn.net/weixin_50096821/article/details/126913045