乐闻世界logo
搜索文章和话题

How can i use vite env variables in vite config js

1个答案

1
  1. Create Environment Variable Files In the root directory of your project, create a .env file 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.

  1. Define Environment Variables Define variables in the .env file 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.

  1. 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.

  1. Type Support For TypeScript type support, define an env.d.ts file and declare the ImportMetaEnv interface:
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.

  1. 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 回复

你的答案