Implementation of multi-environment configuration
The project created with vite does bring a huge performance improvement compared to the original webpack project. A project I practiced myself was also built using vite+typescript+vue3. In actual development scenarios, we often use multi-environment configurations. Generally, projects will at least distinguish between dev and prod environments, and then set a different value for the same parameters in different environments. This capability is also provided in vite, and an example is given in the official documentation:
.env # Load in all cases. # Load in all cases, but will be ignored by git.env.[mode] # Load only in the specified mode.env.[mode].local # Load only in the specified mode,But will be git neglect
1. envDir
According to the official statement, vite will load the .env.[mode] related files we wrote from the environment directory. The default is the project root directory. During actual development, we definitely want to place the configuration file in a separate folder, which can make the project structure clearer. So how to specify the directory where vite loads the environment configuration? We can tell vite the path to load the multi-environment configuration file by specifying envDir in:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' // /config/ export default defineConfig({ envDir: "./viteEnv",// Use relative paths here, absolute paths are actually OK server:{ port: 3001, strictPort: true }, plugins: [vue(), vueJsx()] })
In order to explore the loading of each file, I have created 5 files here:
viteEnv/ |--. |--. |--. |--. |--.
# . # All modes will be loaded, but will be ignored by gitVITE_APP_NAME= venus # . Test environment parameter valuesVITE_OWNER=developer VITE_POSITION=shanghai VENUS_CONNECTION_TIMEOUT = 30000 #. Only loaded in develop mode, but will be ignored by git. The priority in this file is given when the same variable name isVENUS_CONNECTION_TIMEOUT = 10000 # Production environment parameter valueVITE_OWNER=production VITE_POSITION=china VENUS_CONNECTION_TIMEOUT = 3600
Then modify and start different environments through different instructions:
"scripts": { "start": "vite --mode develop", "start:prod": "vite --mode production", "build": "vue-tsc --noEmit && vite build --mode develop", "build:prod": "vue-tsc --noEmit && vite build --mode production", "preview": "vite preview" }
2. Vite rules for identifying environment variables
vite does not pass all variables (or parameters) you write in the configuration file to the client. When we do not have special configuration, it will only recognize the parameters starting with VITE_. We can print them in the entry file:
# is the entry file of my project. The relevant code will be executed on the client side. Print the variables here()
The results are as follows:
{
"VITE_OWNER": "developer",
"VITE_POSITION": "shanghai",
"VITE_APP_NAME": "venus",
"BASE_URL": "/",
"MODE": "develop",
"DEV": true,
"PROD": false,
"SSR": false
}
You can see that only variables starting with VITE_ we wrote can be printed out.
Other variables are several values provided by vite by default, with the following meanings:
: {string} The mode of the application running.
.BASE_URL: {string} The basic URL when deploying the application. It is determined by the base configuration item.
: {boolean} Whether the application is running in production.
: {boolean} Whether the application is running in the development environment (always contrary to).
So is there any way to specify which parameters we want to read? Is this rule starting with VITE_ able to be modified? Actually, it is OK. We have added a new parameter to envPrefix:
export default defineConfig({ envDir: "./viteEnv", envPrefix: ["VITE", "VENUS"], //At this time, we can pass all variables starting with VITE_ and VENUS_ to the client server:{ port: 3001, strictPort: true }, plugins: [vue(), vueJsx()] })
3. What is the priority order of the same parameter name in .env.[mode], ., .env.[mode].local?
We configure the same parameter VENUS_CONNECTION_TIMEOUT in ., ., ., and then print it on the client and find that
.env.[mode].local The highest priority is
.env.[mode] priority
. The lowest priority
4. How to get variable parameters in env on the server
What we see above is the case where vite passes variables in env to the client through. However, we may need to use some parameters on the server side. How to obtain them at this time? Take the file as an example. This is a configuration file that is loaded when the server starts, and the relevant content will be printed to the server console.
vite provides a loadEnv function for loading to related parameters
import { defineConfig,loadEnv } from 'vite' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' //Get configuration parameters on the serverconst console = require("console") (loadEnv('develop', './viteEnv')) // /config/ export default defineConfig({ envDir: "./viteEnv", envPrefix: ["VITE", "VENUS"], server:{ port: 3001, strictPort: true }, plugins: [vue(), vueJsx()] })
In this way, we can get the relevant parameters on the server. It should be noted that the parameters we customize below will not get. If necessary, we need to explicitly specify the prefix in the loadEnv function parameter:
loadEnv('develop', './viteEnv', ["VITE", "VENUS"])
5. Change to production mode
This refers to modifying the program operation mode to the production mode in the non-production mode. The official gave an example of staging. staging represents a pre-issue environment. In some large companies, there will be such an environment for quasi-production verification. When this environment is started, we may hope that the staging application should have a production-like behavior.
Just add a parameter to the .env.[mode] file:
NODE_ENV=production
Then we will find that the PROD value used in vite default parameters to identify production will become true.
{ "VITE_USER_NODE_ENV": "production", "VITE_OWNER": "developer", "VITE_POSITION": "shanghai", "VITE_APP_NAME": "venus", "VENUS_CONNECTION_TIMEOUT": "600", "BASE_URL": "/", "MODE": "develop", "DEV": false, "PROD": true, //It has become a production environment "SSR": false }
Why is this parameter? Judging from the name, this seems to be related to node. Let's print the node's environment variables in it and take a look:
const process = require("process") ()
There is indeed one such parameter in the environment variable. Why is this happening? This value not only turns my environment into production mode, but this parameter also appears in nodejs environment variables. I guess there are two possibilities:
1. NODE_ENV is a special parameter that can be recognized by both vite and nodejs, which can play a role in changing the environment mode.
2. The parameters starting with NODE_ configured in vite's env will be passed to nodejs to control the behavior of nodejs.
So I configured another NODE_DEMO, and then printed it, but found that it did not appear here. It seems that NODE_ENV is indeed a special value.
This project is a training project I am preparing to learn vue3. Students who want to read the complete code can access it through the following address:
/Flnn/venus-admin
The above is the detailed content of Vite multi-environment configuration and variable recognition rules. For more information about Vite multi-environment configuration variable recognition, please pay attention to my other related articles!