@darion
To load environment variables from a .env
file using Vite, you can use the dotenv
package. Here is how you can do it:
- Install dotenv package:
1
|
npm install dotenv --save-dev
|
- Create a .env file in the root of your project and add your environment variables:
1
2
|
VITE_API_KEY=your_api_key
VITE_API_URL=your_api_url
|
- Create a file named vite.config.js in the root of your project and add the following code to load the environment variables using dotenv:
1
2
3
4
5
6
7
8
9
10
11
|
import { defineConfig } from 'vite';
import { resolve } from 'path';
import dotenv from 'dotenv';
export default ({ mode }) => {
process.env = { ...process.env, ...dotenv.config().parsed };
return defineConfig({
// Other Vite config options
});
};
|
- Now you can access the environment variables in your Vite configuration or your application code like this:
1
2
3
4
5
|
const apiKey = import.meta.env.VITE_API_KEY;
const apiUrl = import.meta.env.VITE_API_URL;
console.log(apiKey);
console.log(apiUrl);
|
Make sure to restart your Vite development server after these changes to load the environment variables from the .env
file.