Vue environment variable configuration-process.env

When using vueframeworks, two environments are often used. One is the development environment, which is the environment for local development, and the other is the production environment, which is the environment to be published online.

Normally, the production environment is used for development. If you publish it online, you need to switch the environment to online. It is possible to switch manually, but it will be easy to forget. You can automatically switch the environment by configuring different running commands.

Start below:

The implementation principle of configuring the environment

The implementation principle is to use the (process environment, return an object containing user environment information) attributes in the node.jstop-level object to distinguish and switch environments according to the configuration files of each environment.process.env

Specific examples

1. Install dependencies

npm install process

2.Create .env.dev and .env.prodtwo files

Note that the file must be created under the root directory

.env.devThe contents of the file are as follows:

NODE_ENV = 'development'
VUE_APP_TITLE = 'development'
/* 请求接口地址 */
VUE_APP_INTERFACE_URL="https://xxx"
/* proxy代理地址 */
VUE_APP_PROXYURL='http://xxx'

.env.prodThe contents of the file are as follows:

NODE_ENV='production'
VUE_APP_TITLE='prod'
/* 请求接口地址 */
VUE_APP_INTERFACE="https://xxx"

If necessary .env.test, you can add a test environment file with the following content:

NODE_ENV='production'
VUE_APP_TITLE='test'
/* 请求接口地址 */
VUE_APP_INTERFACE="https://xxx"

3. Set the default environment when the project starts

You only need to modify the required environment after the project startup command. For example npm run dev, --mode devchanging it --mode prodto becomes the development environment

package.jsonPart of the content is as follows:

"scripts":{
	"dev":"vue-cli-service serve --mode dev",//以.env.dev中的接口地址本地运行
	"prod":"vue-cli-service serve --mode prod",//以.env.pro中的接口地址本地运行
	"build": "vue-cli-service build",//以.env.pro中的接口地址打正式包
    "build:test": "vue-cli-service build --mode test"//以.env.test中的接口地址打测试包
}

4. Check whether the environment is configured successfully

Print the current environment in main.jsthe file and the output is successful.
console.log(process.env.NODE_ENV)

Guess you like

Origin blog.csdn.net/m0_55333789/article/details/132715490