Environment Variables in Vite: A Comprehensive Guide 🎯

beginner
22 min

Environment Variables in Vite: A Comprehensive Guide 🎯

Welcome to our deep dive into Environment Variables in Vite! This tutorial is designed for both beginners and intermediates, focusing on practical, real-world examples. Let's get started!

What are Environment Variables? 📝

Environment variables are global configurations that can be set to store sensitive data or dynamic values in your application. They allow you to separate sensitive information like API keys, database URLs, or even environment-specific settings from your code.

Why use Environment Variables in Vite? 💡

Using environment variables in Vite ensures that sensitive information is not exposed in your code, making it more secure. It also allows for easy configuration changes based on the environment (development, testing, production) without modifying your code.

Setting up Environment Variables in Vite 📝

In Vite, environment variables can be set using the vite.config.js file or directly in index.html. Let's explore both methods.

Using vite.config.js

  1. Create a vite.config.js file in the root directory of your project (if it doesn't exist already).

  2. Add the following code to define your environment variables:

javascript
import { defineConfig } from 'vite' import dotenv from 'dotenv' // Load environment variables from .env file dotenv.config() export default defineConfig({ // Other configurations... })
  1. Create a .env file in the root directory to store your variables. For example:
API_KEY=my_api_key BASE_URL=https://my-api.com
  1. Access the environment variables in your code using the import.meta.env object.
javascript
import { defineStore } from 'vuex' export default defineStore({ state() { return { apiKey: import.meta.env.VITE_API_KEY, baseUrl: import.meta.env.VITE_BASE_URL, } }, // Other store configurations... })

Using index.html

In some cases, you might want to set environment variables directly in the index.html file for static content.

  1. In the index.html file, add the following script tag:
html
<script> export const API_KEY = 'my_api_key' export const BASE_URL = 'https://my-api.com' </script>
  1. Access the environment variables in your JavaScript code using the import.meta.glob feature.
javascript
import * as environment from 'vue' console.log(environment.API_KEY) // Output: my_api_key console.log(environment.BASE_URL) // Output: https://my-api.com

Quiz Time 🎯

Quick Quiz
Question 1 of 1

Where can you set environment variables in Vite?

Best Practices 💡

  1. Keep sensitive data out of your code by using environment variables.
  2. Use a .env.local file for local machine-specific configurations.
  3. Use .env.development, .env.testing, and .env.production for different environments.

Practical Example 🎯

Let's create a simple Vue 3 component that fetches data from an API using environment variables.

  1. Install Axios using npm:
npm install axios
  1. Create a new Vue 3 component (DataFetcher.vue):
html
<template> <div> <h1>Data Fetcher</h1> <p v-if="error">{{ error }}</p> <p v-else-if="loading">Loading data...</p> <p v-else>{{ data }}</p> </div> </template> <script setup> import { ref } from 'vue' import axios from 'axios' const data = ref(null) const error = ref(null) const loading = ref(true) // Fetch data using environment variables async function fetchData() { try { const response = await axios.get(`${import.meta.env.VITE_BASE_URL}/api/data`) data.value = response.data loading.value = false } catch (error) { data.value = null error.response ? error.response.data.message : error.message loading.value = false error.value = error.message } } fetchData() </script>

That's it! You now have a good understanding of how to use environment variables in Vite. Happy coding! 🎯

If you found this tutorial helpful, don't forget to give it a thumbs up and share it with your friends! 💪


This tutorial was created for CodeYourCraft, your go-to resource for learning programming. Stay tuned for more engaging, in-depth tutorials like this! 🚀