Welcome to our deep dive into handling environment variables in Vite JS! This guide is perfect for beginners and intermediate learners looking to build robust and scalable projects using Vite. Let's get started! 📝
Environment variables are used to store sensitive data or configuration settings in an application. They allow us to separate sensitive information from our code, making it harder for others to access sensitive data.
To set environment variables in Vite, we use the vite.config.js file. Here's an example:
import { defineConfig } from 'vite'
import dotenv from 'dotenv'
dotenv.config()
export default defineConfig({
// ...
})In the example above, we import the dotenv package and call dotenv.config() to load environment variables from a .env file in the root of our project.
To access environment variables in our code, we use the process.env object:
console.log(process.env.MY_VARIABLE)When running our project in development mode, Vite will read environment variables from the .env.development file. When building our project for production, it will read variables from the .env.production file. This allows us to keep sensitive data out of our Git repositories.
dotenv package to manage environment variables in your Vite project..env.development, .env.production) out of your Git repositories..env files from your repository.Where does Vite look for environment variables in development mode?
We hope this tutorial helped you understand how to handle environment variables in Vite JS. Happy coding! 💡