The environment variable

Front-end project in the development process, usually divided into its environment: development environment, testing environment, online environment

Meaning of environment variables: Configuration variables can be used in different production environments

How do I configure environment variables

You can do the following configuration in the root directory of the project:

├─.env.development ├─.env.production ├─.env.├.[mode] // Mode can be any value you wantCopy the code

Environment files should contain only “key = value” pairs of environment variables, and only variables starting with NODE_ENV, BASE_URL, VUE_APP_ can be used globally as follows:.env.production

Module. exports = {NODE_ENV = 'production' // VUE_APP_VERSION = '0.0.1'}Copy the code

Use of environment variables

You can access configured variables in code like this:

process.env.NODE_ENV
Copy the code

You can configure the default address to be used in different environments:

= 'http://xxx.xxx.xxx.xxx:8080'. The module exports = {VUE_APP_BASE_API / / project default address}Copy the code

The online environment

When a project needs to be packaged to go live, executing NPM run build defaults to using the environment variable in NODE_ENV = ‘production’

model

You can use the corresponding mode according to the environment, each mode corresponds to the corresponding environment configuration under. Env.[mode]

An: chestnut: package. Json

"script": {
    "serve": "vue-cli-service serve"."build": "vue-cli-service build",(default --mode production)"build:one": "vue-cli-service build --mode one"."build:two": "vue-cli-service build --mode two"
}
Copy the code

The corresponding root directory should contain the following configuration:

├─.env.heavy exercises ─.env.heavy exercises ─.env.heavy exercises ─.env.heavy exercises ─.env.heavy exercises ─.env.heavy exercises ─.env.heavy exercises ─.env.heavy exercises ─.env.heavy exercises ─.env.heavy exercises ─.env.heavy exercisesCopy the code

Multiple online environment configuration solutions

Problem: In general, there is only one online environment for project development, but our company is in a special situation. The project needs to be online in each factory, and each factory uses different databases, domain names and ports. If multiple online environments are configured, multiple codes need to be packaged and redeployed every time the project is updated

Solution: We use string concatenation to concatenate the basic address of the project. In the entry function main.js:

Host // Get the current host name const protocol = window.location.protocol // Get the current URL protocol Axios.defaults. baseURL = protocol + '//' + host // concatenates the base addressCopy the code