Setting environment variables in vue is inseparable from the process.env property, so how to set custom environment changes?
It can be set by setting the .env file or by means of process.VUE_CLI_SERVICE
process
The process object is a global (global variable) that provides relevant information and controls the current Node.js process. As an object, it is always available to Node.js applications.
process.env
The process.env property returns an object containing information about the user's environment. And NODE_ENV is one of the environment variables. This variable is mainly used to identify the current environment (production environment, development environment). Relevant properties can be referred to as shown in the figure below
process.VUE_CLI_SERVIC
VUE_CLI_SERVIC is provided by Vue CLI. Viewing process.VUE_CLI_SERVIC
the properties, you can find that it is actually package.json
the configuration content in the Vue project.
In Vue, NODE_ENV can be configured through .env file or .env.[mode] file. After configuration, when running the Vue CLI command ( npm run dev(serve) , npm run build ), the NODE_ENV in this mode will be loaded into it.
Development mode -----process.env.NODE_ENV is development
test mode ------------------process.env.NODE_ENV is test
production mode------- -process.env.NODE_ENV is production
- The default mode can be overridden for the command line by passing the --mode option
"scripts": {
"dev": "vue-cli-service serve",
"build": "vue-cli-service build --mode production",
"build:test": "vue-cli-service build --mode test",
},
- The .vnv.test file
自定义的变量必须以 VUE_APP_ 开头
only has NODE_ENV, BASE_URL and variables starting with VUE_APP_ which will be statically embedded into the client-side code via webpack.DefinePlugin. This is to avoid accidentally exposing a private key on the machine that may have the same name.
If yesvue3+vite 必须使用VITE开头的配置信息 否则无法获取
, example: VITE_NODE_BUILD = "test"
//.vnv.test文件
NODE_ENV=production
VUE_APP_MODE=production
VUE_APP_BUILD=test // 自定义环境变更必须用VUE_APP_开头
The corresponding relationship diagram is shown
Precautions
When running the vue-cli-service command, all environment variables are loaded from the corresponding environment file.
If the NODE_ENV variable is not included inside the file, its value will depend on the mode, for example, it is set to "production" in production mode, set to "test" in test mode, and the default is "development" if no
configuration .env.
file If so, --mode custom
when processing by setting a custom mode , build
you need to pay attention to setting NODE_ENV to production
, otherwise it cannot be packaged normally
const mode = process.VUE_CLI_SERVICE.mode === 'development' ? 'development' : 'production'
process.env.NODE_ENV = mode
process.env.VUE_APP_MODE = mode
let publicPath =process.VUE_CLI_SERVICE.mode === 'test' ? '/ag-collect-server-springcloud' : '/ag-collect'