Vue project configuration environment variables

Understanding of environment variables:
In projects where the front and back ends are separated, there will be many front-end environments: test environment, grayscale environment, formal environment, etc. When our project goes online again, it will be released to different environments for testing. When each When the environment needs to be packaged, manually modifying the configuration is cumbersome and inevitably makes mistakes. For example, the server address corresponding to each environment is different. So use environment variables to distinguish between different environments.

Solution: Create .env.xxx files in the root directory, such as .env.test test environment, .env.development development environment, .env.production formal environment, and .env.long grayscale environment.

Step 1: Create the .env.development and .env.production files, which are at the same level as the package.json file. These two are provided by the environment. In order to meet the environment mentioned above, we need to define the env file ourselves, such as .env .dev (development environment) .env.prod (official environment) .env.long (grayscale environment) .env.test (test environment)
insert image description here
Step 2: Configure the interface address in the .env configuration file, by assigning a value to VUE_APP_BASE_URL, You can write more than one name, but please note that it must start with VUE_APP_ (VUE_APP_xxx), as shown in the following code

# env.dev文件
VUE_APP_BASE_URL = "//dev.api.saas.com"
#.env.prod文件
VUE_APP_BASE_URL = "//api.saas.com"
#.env.long文件
VUE_APP_BASE_URL = "//long.api.saas.com"
#.env.test文件
VUE_APP_BASE_URL = "//test.api.saas.com"

Step 3: Configure
the default configuration in package.json

"scripts": {
    
    
    "serve": "vue-cli-service serve",//默认就是 development开发环境
    "build": "vue-cli-service build", //默认就是 production生产环境
  },

Configure the custom env file in package.json, add the corresponding serve and build commands, and use the --mode option flag to override the default mode used by the command --mode dev
must have a corresponding env file, if it cannot be found, it will default .env.develpment, the name behind the server is taken randomly.

Configure code in package.json

"scripts": {
    
    
    "serve:dev": "vue-cli-service serve --mode dev ",//就是 env.dev 环境
    "serve:prod": "vue-cli-service serve --mode prod", //就是 env.prod 环境
    "serve:long": "vue-cli-service serve --mode long",//就是 env.long 环境
    "serve:test": "vue-cli-service serve --mode test",//就是 env.test 环境
 
    "build:dev": "vue-cli-service build --mode dev",//就是 env.dev 环境
    "build:prod": "vue-cli-service build --mode prod",//就是 env.prod 环境
    "build:long": "vue-cli-service build --mode long",//就是 env.long 环境
    "build:test": "vue-cli-service build --mode test",//就是 env.test 环境
  },

Guess you like

Origin blog.csdn.net/m0_49016709/article/details/125298628