existVueIn the project, multi-environment configuration is a common requirement, which is mainly used to distinguish API addresses, keys and other configurations in different environments such as development, testing, and production. Here are the basic steps for how to configure a multi-environment project based on Vue CLI:
1. Create environment variable file
In the project's root directory, create.env
File family, such as.
(Local development environment),.
(Development environment),.
(Test environment),.
(Production environment). Vue CLI will automatically load the corresponding configuration file according to the current mode.
2. Set variables in the environment file
In each.env
In the file, define the required environment variables, for example:
-
# .
-
VUE_APP_API_URL=http://
Note that the name of the environment variable must beVUE_APP_
At the beginning, this is the prefix that the Vue CLI recognizes environment variables.
3. Use environment variables in the project
In the code, you can use.VUE_APP_API_URLTo access the environment variables defined above.
4. Use`vue-cli-service` command line tool building project
In different environments, you can use different commands to build projects, such as:
-
# Development Environment
-
vue-cli-service build --mode development
-
-
# Production environment
-
vue-cli-service build --mode production
5. Scripts in configuration
To simplify the build process, you can configure the corresponding script commands in the scripts section in the ``scripts` section:
-
"scripts": {
-
"serve": "vue-cli-service serve",
-
"dev": "vue-cli-service serve --mode development",
-
"prod": "vue-cli-service serve --mode production",
-
"build:dev": "vue-cli-service build --mode development",
-
"build:prod": "vue-cli-service build --mode production"
-
}
This will be usednpm run build:devornpm run build:prodTo perform environment-specific construction.
-
//run
-
npm run dev
-
-
npm run prod
-
-
//Pack
-
npm run build:dev
-
-
npm run build:prod
6. Use environment variables
const apiUrl = process.env.VUE_APP_API_URL;