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!
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.
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.
In Vite, environment variables can be set using the vite.config.js file or directly in index.html. Let's explore both methods.
vite.config.jsCreate a vite.config.js file in the root directory of your project (if it doesn't exist already).
Add the following code to define your environment variables:
import { defineConfig } from 'vite'
import dotenv from 'dotenv'
// Load environment variables from .env file
dotenv.config()
export default defineConfig({
// Other configurations...
}).env file in the root directory to store your variables. For example:API_KEY=my_api_key
BASE_URL=https://my-api.com
import.meta.env object.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...
})index.htmlIn some cases, you might want to set environment variables directly in the index.html file for static content.
index.html file, add the following script tag:<script>
export const API_KEY = 'my_api_key'
export const BASE_URL = 'https://my-api.com'
</script>import.meta.glob feature.import * as environment from 'vue'
console.log(environment.API_KEY) // Output: my_api_key
console.log(environment.BASE_URL) // Output: https://my-api.comWhere can you set environment variables in Vite?
.env.local file for local machine-specific configurations..env.development, .env.testing, and .env.production for different environments.Let's create a simple Vue 3 component that fetches data from an API using environment variables.
npm install axios
DataFetcher.vue):<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! 🚀