What are environment variables
Variables that change according to the current code environment are called environment variables . For example, set BASE_URL to different values in the production environment and the development environment to request interfaces in different environments.
Environment variables are generally accessible globally. In webapck, we may have seen such code
// webpack.config.js
module.exports = {
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development'
}
process.env.NODE_ENV is an environment variable.
- process.env is an API provided by Nodejs, which returns an object that contains all the environment variables of the current Shell. For example, process.env.HOME returns the user's home directory.
- process.env for webpack environment configuration: https://www.yuque.com/persagy/mkk933/qycy0e
How to use environment variables in vite
Environment variables and process.env
The use of environment variables implements different logic based on different environments. For example, set BASE_URL to different values in the production environment and the development environment to request interfaces in different environments.
But it should be noted that the identification of environment variables here is carried out on the browser side, and the browser performs different logics according to different environment variables!
In vue2, webpack helped us do the processing, so that the browser can directly recognize the process.env variable of node, thus realizing the function of the browser to recognize the environment variable.
- In vite, our code runs in the browser environment, so the process.env variable cannot be recognized. (This means that the way to identify environment variables in vite is different from that in webpack)
- vite.config.js runs in the node environment, so process.env variables can be recognized
Look at the following example:
we print process.env in main.js, the browser does not recognize process.env, and will report an error
console.log(' process.env: ', process.env);
vite.config.js runs in the node environment and can print out process.env
So, how to identify environment variables in vite?
Environment variables in vite
Vite exposes environment variables on a special import.meta.env object. Here are some built-in variables that can be used in all cases:
- import.meta.env.MODE : {string} The mode the application runs in .
- import.meta.env.BASE_URL : {string} The base URL when deploying the application. It is determined by the base configuration item .
- import.meta.env.PROD : {boolean} Whether the application is running in production environment .
- import.meta.env.DEV : {boolean} Whether the application is running in the development environment (always the opposite of import.meta.env.PROD).
- import.meta.env.SSR : {boolean} Whether the application is running on the server .
Let's print it in main.js
console.log(' import.meta.env.MODE: ', import.meta.env.MODE);
console.log(' import.meta.env.BASE_URL: ', import.meta.env.BASE_URL);
console.log(' import.meta.env.PROD: ', import.meta.env.PROD);
console.log(' import.meta.env.DEV: ', import.meta.env.DEV);
console.log(' import.meta.env.SSR: ', import.meta.env.SSR);
Note: These variables cannot be accessed in vite.config.js in the running environment
So, how do we customize some environment variables?
Custom environment variables in vite
Vite has built-in dotenv , a third-party library, dotenv will automatically read the .env file, and dotenv loads additional environment variables from the following files in your environment directory:
.env # will be loaded in all cases.env
.[mode] # only loaded in the specified mode
by default
- npm run dev will load the configuration in .env and .env.development
- npm run build will load the configuration in .env and .env.production
- mode can be overridden with the --mode option on the command line.
The loaded environment variables are also exposed to the client source code as strings through import.meta.env . To prevent accidentally leaking some environment variables to the client, only variables prefixed with VITE_ will be exposed to vite-processed code.
Let's verify:
We create a .env file in the root directory of the project and write the test content;
HELLO = "小伙子,我是base数据"
VITE_HELLO = "小伙子,我是base数据"
Create a .env.development file and write the test content;
HI = "小伙子,我是development数据"
VITE_HI = "小伙子,我是development数据"
Create a .env.production file and write the test content;
MD = "小伙子,我是production数据"
VITE_MD = "小伙子,我是production数据"
Then print it in main.js
console.log(' HI: ', import.meta.env.HI);
console.log(' VITE_HI: ', import.meta.env.VITE_HI);
console.log(' HELLO: ', import.meta.env.HELLO);
console.log(' VITE_HELLO: ', import.meta.env.VITE_HELLO);
console.log(' MD: ', import.meta.env.MD);
console.log(' VITE_MD: ', import.meta.env.VITE_MD);
Run the npm run dev command, and observe the browser print results
Since we are executing run dev and the mode belongs to development , variables prefixed with VITE_ in .env and .env.development will be recognized.
Vite environment variable configuration advanced
Load a custom .env file
Based on the design mode of vite, the .env files corresponding to the development mode (development) and production mode (production) can be loaded in the project by default.
If we customize a test environment and want to load the environment variables in .env.test, what should we do?
1. The specified mode mode displayed
Refer to the mode sharing configuration of vite | Vite official Chinese document
For convenience, we directly configure the command "test" in package.json : "vite --mode test" ,
"scripts": {
"test": "vite --mode test",
"dev": "vite",
"build": "vite build"
},
2. Create a .env.test file in the root directory
VITE_HI = "1111111111111111111111111111111111"
Print this environment variable in main.js console.log(' VITE_HI: ', import.meta.env.VITE_HI);
Run the npm run test command and observe the browser console results.
It can be seen that at this time, the environment variables in our custom test environment are printed.
Change the default address of .env
Our current .env files are all created in the root directory. If there are too many .env.XX files, our project directory will appear messy. Can we put .env in a unified folder?
Can be changed by envDir configuration! Reference: Shared Configuration | Vite Official Chinese Documentation
envDir The directory to load .env files from. Can be an absolute path or a path relative to the project root.
- Type: string
- Default: root
For example, we configure it like this in vite.config.js
import { defineConfig } from "vite";
export default defineConfig( {
envDir:"env"
});
Then, all .env.xxx files can be placed under the env folder of the project root directory.
Change the VITE_ prefix of the environment variable
If you think the VITE_ prefix is not enough, and you want to change it, how should you change it?
Use envPrefix configuration to change! Reference: Shared Configuration | Vite Official Chinese Documentation
Environment variables starting with envPrefix will be exposed in your client source code through import.meta.env.
- Type: string | string[]
- Default: VITE_
Safety Precautions
envPrefix should not be set to the empty string ' ' , this will expose all your environment variables, leading to accidental disclosure of sensitive information. Vite will throw an error when it detects that the configuration is ' ' .
Special handling of vite loading environment variables
There is a global variable process.env in the node environment. Based on the loading principle of dotenv, the environment variables set in .env can theoretically be printed in vite.config.js.
We create a .env file in the project, configure the environment variables, try
HELLO = "小伙子,你很行啊"
We do printing in vite.config.js.
import { defineConfig } from "vite";
export default defineConfig(({ command, mode, ssrBuild }) => {
console.log("process.env: ", process.env.HELLO);
return {
//....一些vite配置
};
});
The strange thing is that process.env.HELLO is not printed (note: it is now a node environment), why?
Through the examples in the previous sections, we can know that the envDir option will affect the location where the .env file is loaded. Therefore, Vite does not load the .env file by default , because these files need to be configured after Vite is configured to determine which one to load.