Use .env files can be easily configured and server development and debugging environment official deployed a production environment using two different sets of configuration files to achieve code without switching back and forth path needs to be accessed api interface.
Official Documents
https://cli.vuejs.org/zh/guide/mode-and-env.html
Create a file .env
Were created in the root directory of vue project .env.development
and .env.production
two text files are used in development and production environments
.env.development
Document reads as follows:
VUE_APP_API_HOST=127.0.0.1
.env.production
Document reads as follows:
VUE_APP_API_HOST=10.41.56.121
Note that .env
variable names must be at VUE_APP_
the beginning
The variable access .env
For example, in main.js
the configuration axios
request can be written as root
axios.defaults.baseURL = `http://${process.env.VUE_APP_API_HOST}:8000/`
Notice that a formatted string syntax ES6 is, with the front and ~
the key input symbols `
In this way the local use yarn serve
will be running on a test server to access .env.development
variables defined, and in yarn build
time will use .env.production
the contents of variables.
Side story
Curious about this ~
key input 反单引号
(I will not call) Jiaosha name, found that foreigners like to call it Grave accent
, it should be called translated重音符