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

How can I get Vite env variables?

1个答案

1
  1. Define Environment Variables: In the project root directory, create a .env file to define your environment variables. Vite requires environment variables to start with VITE_. For example, create a .env file and add the following content:
shell
VITE_API_URL=https://myapi.com VITE_API_KEY=secretkey

Here, two environment variables are defined: VITE_API_URL and VITE_API_KEY.

  1. Access Environment Variables: In your Vite project code, use import.meta.env to access the defined environment variables. For example:
javascript
const 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.

  1. Modes and Environment Variable Files: For different environments (such as development and production), prepare different .env files. For example, .env.development and .env.production. When you run or build the project, Vite automatically loads the corresponding .env file based on the current mode.

  2. Type Declaration (Optional): To get better type hints in TypeScript projects, declare the types of environment variables in the env.d.ts file:

typescript
interface 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.development file:

    shell
    VITE_API_URL=http://localhost:3000 VITE_API_KEY=development-secret-key
  • In the .env.production file:

    shell
    VITE_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.

2024年6月29日 12:07 回复

你的答案