@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
|
npm install dotenv --save-dev |
1 2 |
VITE_API_KEY=abc123 VITE_BASE_URL=http://example.com |
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 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.