background

During project deployment, we need to use different variables in our test and production environments. Vue-cli provides the vue-cli-service build package command, but the default value of the vue-cli-service build environment variable is production. NPM run build package, we want to implement different environment using different variables, can not be implemented at the moment.

Vue cli – service is introduced

Vue-cli-service Describes how to set the following parameters in package.json when vue-cli generates a project:

  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build"
}
Copy the code

Vue-cli-service serve starts a development server. By default, the environment mode specified is development. Vue-cli-service build will produce a production-ready package in the dist/ directory, with JS/CSS/HTML compression, and automatic Vendor Chunk splitting for better caching. In the root directory of the project we can create different schema files:

Env.[mode] # is loaded only in the specified mode. Git ignores itCopy the code

Generally speaking, we have a local environment, a test environment, and an online environment, so we need to create three schema files.

  • .env.developmentDevelopment environment Pattern
VUE_APP_ENV = 'development' // Variables starting with VUE_APP_ are statically embedded in client-side packages by webpack.defineplugin.Copy the code
  • .env.testTest environment mode
// Environment variables (environment variables are related to packaging, production is compressed code, etc.) The variables that are really relevant for each environment are the ones below starting with VUE_APP.) NODE_ENV=production // variables starting with VUE_APP_ are statically embedded in client-side packages by webpack.defineplugin 'test'Copy the code
  • .env.productionOnline Environment Mode
VUE_APP_ENV = 'production' // Variables starting with VUE_APP_ are statically embedded in client-side packages by webpack.defineplugin.Copy the code

Vue -cli-service build is executed. The default mode is production, corresponding to.env.production.

To configure the test environment, add a script under scripts:

"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "build-test": "vue-cli-service build --mode test"
}
Copy the code

When the test environment is packaged and built, run NPM run build-test.

Index.html uses environment variables

In index. HTML, you can run <%= process.env.vue_app_xxx %> to obtain environment variables configured in different modes.

validation

You can check the corresponding environment based on the corresponding environment variables in different modes