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

How to load environment variables from env file using vite

1个答案

1

In Vite, loading environment variables from .env files is a straightforward process. Vite natively supports loading environment variables by placing .env files in the project root directory. Below are the steps and details:

Step 1: Create the .env File

First, create a .env file in the project root directory. If you need to differentiate between environments, such as development or production, you can create multiple files, for example:

  • .env: Default environment variables file loaded for all environments.
  • .env.local: Environment variables file specific to local development, not tracked by Git.
  • .env.development: Used only in development environments.
  • .env.production: Used only in production environments.

Step 2: Define Environment Variables

In the .env file, you can define environment variables. These variables must be prefixed with VITE_ to be recognized by Vite in the project. For example:

env
# .env VITE_API_URL=https://api.example.com VITE_APP_TITLE=My Vite App

Step 3: Use Environment Variables in the Project

In your JavaScript or TypeScript code, you can access these environment variables via the import.meta.env object, as shown:

javascript
console.log(import.meta.env.VITE_API_URL); // Output: https://api.example.com console.log(import.meta.env.VITE_APP_TITLE); // Output: My Vite App

Example

Suppose we are developing a frontend application that needs to call an API; we might want to use different API endpoints based on the environment. In this case, we can set the environment variables as follows:

.env.development

env
VITE_API_URL=https://dev.api.example.com

.env.production

env
VITE_API_URL=https://api.example.com

Then in the code:

javascript
async function fetchData() { const apiUrl = import.meta.env.VITE_API_URL; const response = await fetch(`${apiUrl}/data`); return response.json(); } fetchData().then(data => { console.log(data); });

In the above example, depending on the environment, the fetchData function fetches data from different API endpoints.

Important Notes

  • When modifying .env files, you typically need to restart the Vite development server for the new variables to take effect.
  • All environment variables exposed in client-side code should be handled with caution to avoid including sensitive information, as they can be seen in the built frontend code.
  • For security, .env.local files are typically used to store sensitive information and should be added to .gitignore to prevent them from being committed to version control.

This explanation demonstrates how to load environment variables from .env files in Vite, providing a concrete example through a practical application scenario.

2024年6月29日 12:07 回复

你的答案