Use the .env file to define global variables in VUE

In normal vue development, we may use the same field on multiple pages, or the root path of a web page, which is not easy to maintain when directly written in the code. When subsequent modifications are made, many pages need to be modified, so we I wonder if there is a way to define a global variable, which can be used directly in each vue file. This article is about how to use the .env file to define global variables.

1. What is the .env file?

In the vue project, env is a global configuration file that can store variables in different environments. Use vue-cli to build a project, and a .env file will be created in the root directory by default.

.env                # 在所有的环境中被载入
.env.local          # 在所有的环境中被载入,但会被 git 忽略
.env.[mode]         # 只在指定的模式中被载入
.env.[mode].local   # 只在指定的模式中被载入,但会被 git 忽略

The value of mode can be development (development environment), production (production environment), test (test environment), and they are only loaded in the corresponding mode.

2. Configure the .env file

We configure global variables in the .env file, which need to be defined in the form of key-value pairs, such as

VUE_APP_BAIDU_URL='www.baidu.com'

And the name of the variable needs to start with VUE_APP_  , otherwise undefined will be obtained in the subsequent variable acquisition.

VUE_APP_TEST_SUCCESS='www.baidu.com' //正确
APP_TEST_SUCCESS='www.baidu.com' //错误
TEST_SUCCESS='www.baidu.com' //错误

Note: The .env environment file is loaded by running the vue-cli-service command, so if the environment file changes, you need to restart the service.

3. Vue gets global variables

The variable VUE_APP_BAIDU_URL='www.baidu.com' is set in the .env file  ,

In vue, you only need to use process.env.VUE_APP_BAIDU_URL to get it. No need to import other packages, very convenient.

Guess you like

Origin blog.csdn.net/weixin_44220970/article/details/129328696