A.

  • Various environment configurations

2. Implement

In project development, there are generally 2 to 3 sets of environments, such as development environment, pre-production environment, production environment, etc. Accordingly, we will also make corresponding configurations for various environments in the project to meet development requirements.

1. Vue-cli3 mode (Mode)

Passing the mode command into vue-cli-service will load the corresponding environment file, thus generating project code for different environments according to the packaging command.

vue-cli-service build --mode development
Copy the code

2. Environment files

Only NODE_ENV, BASE_URL, and variables starting with VUE_APP_ will be statically embedded in the client-side code via webpack.defineplugin. This is to avoid accidentally exposing a private key on the machine that might have the same name.

When vue-cli-service build –mode development is run,.env.development and.env.development.local are loaded

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

Environment files are key-value pairs of ways to define variables

FOO=bar
VUE_APP_NOT_SECRET_CODE=some_value
Copy the code

The command description in package.js

. "scripts": { "serve:dev": "vue-cli-service serve --mode dev", "serve:pre": "vue-cli-service serve --mode pre", "serve:prd": "vue-cli-service serve --mode prd", "build:dev": "vue-cli-service build --mode dev", "build:pre": "vue-cli-service build --mode pre", "build:prd": "vue-cli-service build --mode prd", "lint": "vue-cli-service lint" }, ...Copy the code

3. Take three environments as examples

Development environment, pre-production environment, production environment

  • Create three environment files
.env.dev
.env.pre
.env.prd
Copy the code
  • Setting environment Variables

Set the NODE_ENV and VUE_APP_ENV variables, which can be used normally in code

// .env.dev NODE_ENV=dev VUE_APP_ENV=dev // .env.pre NODE_ENV=production VUE_APP_ENV=pre // .env.prd NODE_ENV=production  VUE_APP_ENV=prdCopy the code
  • Use environment variables in your code
<template> ... </template> <script> ... Created () {console.log(' current environment variable NODE_ENV:', process.env.node_env); Console. log(' current environment variable VUE_APP_ENV:', process.env.vue_app_env); } } </script>Copy the code
  • The command description in package.js
. "scripts": { "serve:dev": "vue-cli-service serve --mode dev", "serve:pre": "vue-cli-service serve --mode pre", "serve:prd": "vue-cli-service serve --mode prd", "build:dev": "vue-cli-service build --mode dev", "build:pre": "vue-cli-service build --mode pre", "build:prd": "vue-cli-service build --mode prd", "lint": "vue-cli-service lint" }, ...Copy the code