Vue dynamically packages BASE_API according to the environment

The project needs to run in different environments, such as development, testing, production, etc., but the service address requested in each environment is not determined. In order to avoid frequent switching of requested addresses and related configuration errors, the new vue-cli Scaffolding does not directly provide configuration options, what should I do? The common method is to implement automatic switching after the environment baseapi is configured.

1. Create .env series files.
First, we create 3 new files in the root directory,
namely .env.development, .env.test, and .env.production.

.env.development 开发环境
.env.test 测试环境
.env.production 模式用于build项目,线上环境

The content of the .env.development file is as follows:

# 页面标题
VUE_APP_TITLE = 'TEST PROJECT'

#环境信息
NODE_ENV = 'development'
#开发环境的URL
VUE_APP_SERVER_URL = 'http://10.20.30.40:8081'
#配置代理info
VUE_APP_BASE_API = 'http://10.10.10.14:8888/'

# 路由懒加载
VUE_CLI_BABEL_TRANSPILE_MODULES = true

What we need to configure here is the VUE_APP_BASE_API attribute. When used in other places, just use process.env.VUE_APP_BASE_API to obtain it, such as:

const service = axios.create({
    
    
  baseURL: process.env.VUE_APP_BASE_API,
  // timeout: 10000,
  headers: {
    
     'Content-Type': 'application/json' }
})

Just like the following, the .env file only needs to declare the environment, and there is no need to configure the VUE_APP_BASE_API attribute, because it becomes a global variable that can be used anywhere, and it will automatically assign the baseURL according to the environment

// 环境的切换
if (process.env.NODE_ENV === 'development') {
    
    
  axios.defaults.baseURL = 'http://10.11.12.13:8081/'
} else if (process.env.NODE_ENV === 'test') {
    
    
  axios.defaults.baseURL = 'http://10.20.30.40:8082/'
} else if (process.env.NODE_ENV === 'production') {
    
    
  axios.defaults.baseURL = 'http://10.21.32.43:8083/'
}

Now that the configuration is complete, how to use it during project operation? What you need here is the running command.

  1. Configure the packaging command in package.json:
{
    
    
  "name": "",
  "version": "1.0.0",
  "description": "test project",
  "scripts": {
    
    
    "serve": "vue-cli-service serve",
    "build:test": "vue-cli-service build   --mode test",
    "build:prod": "vue-cli-service build   --mode production",
    //原来的"build": "vue-cli-service --mode build",
  },
  "dependencies": {
    
    },
}
  1. Just run the command in the command box, for example: npm run build:test to switch to the address of the test environment

Note: The command –mode in the package is consistent with the file .env file names ".env.test" and ".env.production" added in the root directory of the project in the first step.

Guess you like

Origin blog.csdn.net/kirinlau/article/details/129078686