- Define Environment Variables:
In the project root directory, create a
.envfile to define your environment variables. Vite requires environment variables to start withVITE_. For example, create a.envfile and add the following content:
shellVITE_API_URL=https://myapi.com VITE_API_KEY=secretkey
Here, two environment variables are defined: VITE_API_URL and VITE_API_KEY.
- Access Environment Variables:
In your Vite project code, use
import.meta.envto access the defined environment variables. For example:
javascriptconst apiUrl = import.meta.env.VITE_API_URL; const apiKey = import.meta.env.VITE_API_KEY;
This code retrieves the values of the VITE_API_URL and VITE_API_KEY environment variables defined in the .env file earlier.
-
Modes and Environment Variable Files: For different environments (such as development and production), prepare different
.envfiles. For example,.env.developmentand.env.production. When you run or build the project, Vite automatically loads the corresponding.envfile based on the current mode. -
Type Declaration (Optional): To get better type hints in TypeScript projects, declare the types of environment variables in the
env.d.tsfile:
typescriptinterface ImportMetaEnv { readonly VITE_API_URL: string; readonly VITE_API_KEY: string; // More environment variables... } interface ImportMeta { readonly env: ImportMetaEnv; }
This allows TypeScript to know which environment variables are available and provides the correct types for them.
For example, suppose we are developing a frontend application that needs to call an API. We might need a base URL for the API and an API key. In development and production environments, these values are typically different. We can set up the environment variables as follows:
-
In the
.env.developmentfile:shellVITE_API_URL=http://localhost:3000 VITE_API_KEY=development-secret-key -
In the
.env.productionfile:shellVITE_API_URL=https://production-api.com VITE_API_KEY=production-secret-key
When running or building the application in different environments, Vite automatically loads the correct environment variable file, and your code can seamlessly use these variables to make API calls.