Welcome to our deep dive into custom environment variables in Vite JS! This lesson is perfect for both beginners and intermediates looking to explore and master this essential concept. Let's get started!
Environment variables are simple key-value pairs that store configuration data for your application. They help you manage application settings and make your code more flexible and reusable.
dotenv PackageFirst, you need to install the dotenv package, which allows you to load environment variables from a .env file.
npm install dotenv.env FileCreate a .env file in the root directory of your project. Add your environment variables like this:
VITE_API_KEY=my_api_key
VITE_DB_USERNAME=my_username
VITE_DB_PASSWORD=my_password
To access the environment variables in your Vite JS project, import the dotenv package and call dotenv.config() at the top of your main JavaScript file:
import dotenv from 'dotenv';
dotenv.config();Now, you can access the variables using the process.env object:
console.log(process.env.VITE_API_KEY); // my_api_keyLet's build a simple weather app that fetches data from an API using a custom environment variable for the API key.
import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();
// Fetch weather data using the API key from the .env file
async function getWeatherData() {
const apiKey = process.env.VITE_API_KEY;
const response = await axios.get(
`http://api.openweathermap.org/data/2.5/weather?q=London&appid=${apiKey}`
);
// Do something with the weather data...
}
getWeatherData();What is the purpose of using environment variables in Vite JS?
That's all for now! With this lesson, you're well-equipped to start using custom environment variables in your Vite JS projects. Happy coding! 😊