.env.production)Welcome to the fourth lesson of our Vite JS tutorial! Today, we'll dive into mode-specific configurations, focusing on the .env.production file. By the end of this lesson, you'll understand how to manage environment variables for your production environment.
Let's start with the basics! šÆ
In web development, environment variables allow us to store sensitive information, like API keys and database passwords, securely. They are crucial for separating configuration data from our code, making our applications more secure and easier to manage.
In Vite, we can manage environment variables through the .env files. These files are used to configure the environment variables for both the development and production modes. Today, we'll focus on the .env.production file, which contains variables specific to our production environment.
.env.production fileTo create a .env.production file, follow these simple steps:
.env.production (don't forget the .env prefix!).Let's create an example .env.production file:
VITEAPP_API_KEY=abcdefghijklmnop
DATABASE_URL=mydatabase.com
š” Pro Tip: The variable names should follow the naming convention VITEAPP_<VARIABLE_NAME>. This convention helps Vite identify environment variables correctly.
Now that we have our .env.production file, let's see how to access these variables in our Vite project.
First, we need to install dotenv as a dev dependency:
npm install dotenv
Next, import the dotenv package at the beginning of your main JavaScript (.jsx or .tsx) file:
import dotenv from 'dotenv';
dotenv.config();Now we can access our environment variables using the process.env object:
console.log(process.env.VITEAPP_API_KEY);
console.log(process.env.DATABASE_URL);In Vite, the production build is triggered by running the following command in your terminal:
npm run build
During the build process, Vite will automatically read the .env.production file and set the environment variables for the production build.
We've learned about mode-specific configurations in Vite, focusing on the .env.production file. We've created a .env.production file, accessed environment variables, and built our application for production.
š Note: It's important to keep sensitive information secure by not committing the .env.production file to version control. You can use the .gitignore file to ignore this file from version control.
What is the purpose of the `.env.production` file in Vite?
Stay tuned for our next lesson, where we'll dive into Vite's plugins and how to use them to enhance our project! š