Process.env front-end environment variable configuration tutorial

1. Why configure environment variables

Company, there is a general development project version, test version, grayscale version and online versions, each version will correspond to the same or different data database, the API address. In order to facilitate management, we usually make it into the form of configuration files, and load different files according to different environments. If you manually modify the path to load the configuration file in the code , it is okay, but it is too troublesome, the most important thing is very low (invisible force, the most deadly).

 

Second, the realization principle

Using the process.env (process environment, returns an object containing user environment information.) property in the node js top-level object, distinguish and switch environments according to the configuration files of each environment

 

3. Specific operations (take the vue project as an example)

1. Installation dependencies

npm install process

2. Add five files to the root directory (increased or decreased according to your own situation), .env and .env.dev and .env.pre and .env.prod and .env.sit and .env.uat, which are respectively the default configuration , Local development configuration, gray configuration, production configuration, test configuration 1, test configuration 2, (ps:  vue _APP is a unified logo, the extension name can be taken anytime)

.env

VUE_APP_TITLE='dev'

.dev

NODE_ENV = 'development'
VUE_APP_TITLE = 'development'
/*请求接口地址*/
VUE_APP_INTERFACE_URL="https://xxx"
/*首页地址*/
VUE_APP_URL="http://xxx"
/*proxy代理地址*/
VUE_APP_PROXYURL='http://xxx'

.prod

NODE_ENV = production
VUE_APP_TITLE = 'prod'
/*请求接口地址*/
VUE_APP_INTERFACE_URL="https://xxx"
/*首页地址*/
VUE_APP_URL="http://xxx"

 

3. Set the default environment when the project starts

You only need to modify the required environment after the project startup command. For example, I am npm  run dev, and change --mode dev to --mode uat to do
package. js on

"scripts": {
    "dev": "vue-cli-service serve --mode dev",
    "build": "vue-cli-service build --mode dev",
    "lint": "vue-cli-service lint",
    "build-sit": "vue-cli-service build --mode sit",
    "build-uat": "vue-cli-service build --mode uat",
    "build-pre": "vue-cli-service build --mode pre",
    "build-prod": "vue-cli-service build --mode prod"
  },

 

4. Check whether the environment is successfully configured

Print the current environment in main.js, the output is successful

console.log(process.env.NODE_NEV)

Guess you like

Origin blog.csdn.net/weixin_43844696/article/details/110651394