How to use the .env files config from webpack to vite?

Member

by mac , in category: Javascript , a month ago

How to use the .env files config from webpack to vite?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , a month ago

@mac 

Vite does not directly support loading environment variables from a .env file like Webpack does. However, you can still load environment variables in Vite by using the dotenv package.


Here is how you can do that:

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


  1. Create a .env file at the root of your project and add your environment variables. For example:
1
2
VITE_API_KEY=abc123
VITE_BASE_URL=http://example.com


  1. Create a script to load the dotenv package and configure the environment variables in your Vite configuration file (vite.config.js). Here is an example of how you can do that:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { defineConfig } from 'vite';
import dotenv from 'dotenv';

// Load environment variables
dotenv.config();

export default defineConfig({
  define: {
    // Pass the environment variables to Vite
    'import.meta.env.VITE_API_KEY': process.env.VITE_API_KEY,
    'import.meta.env.VITE_BASE_URL': process.env.VITE_BASE_URL,
  },
});


  1. Make sure to update your code to use the environment variables like so:
1
2
3
4
5
6
// Access the environment variables using import.meta.env
const apiKey = import.meta.env.VITE_API_KEY;
const baseURL = import.meta.env.VITE_BASE_URL;

console.log(apiKey);
console.log(baseURL);


That's it! Now you should be able to load environment variables from a .env file in your Vite project.