How to load environment variables from .env file using vite?

Member

by darion , in category: Javascript , 9 months ago

How to load environment variables from .env file using vite?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 9 months ago

@darion 

To load environment variables from a .env file using Vite, you can use the dotenv package. Here is how you can do it:

  1. Install dotenv package:
1
npm install dotenv --save-dev


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


  1. 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
  });
};


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