- Create Environment Variable Files
In the root directory of your project, create a
.envfile to define environment variables. To distinguish environments, use specific files such as:
.env: Loaded in all environments.env.local: Loaded in all environments but ignored by Git.env.[mode]: Loaded only in the specified mode.env.[mode].local: Loaded only in the specified mode and ignored by Git
Here, [mode] can be development, production, or any custom mode name.
- Define Environment Variables
Define variables in the
.envfile as follows:
shell# .env file VITE_APP_TITLE=My App VITE_API_URL=https://api.example.com
Vite requires all variables to start with VITE_ to prevent accidental exposure of sensitive data.
- Use Environment Variables in Your Project
Access variables in JavaScript or TypeScript files using
import.meta.env, for example:
javascript// Accessing environment variables console.log(import.meta.env.VITE_APP_TITLE); // Output: My App console.log(import.meta.env.VITE_API_URL); // Output: https://api.example.com
This allows you to adjust variables per environment without modifying code.
- Type Support
For TypeScript type support, define an
env.d.tsfile and declare theImportMetaEnvinterface:
typescript// env.d.ts file interface ImportMetaEnv { readonly VITE_APP_TITLE: string; readonly VITE_API_URL: string; // Add more variables as needed } interface ImportMeta { readonly env: ImportMetaEnv; }
This provides auto-completion and type checking.
- Use Environment Variables in HTML
In
index.html, Vite replaces variables during the build process:
html<!-- index.html --> <title>%VITE_APP_TITLE%</title>
During the build, %VITE_APP_TITLE% is substituted with the actual variable value.
By following these steps, you can manage configurations for different environments in your Vite project. This approach enhances flexibility while safeguarding sensitive data.
2024年6月29日 12:07 回复