Vite JS Tutorial: Mode-Specific Config (`.env.production`)

beginner
12 min

Vite JS Tutorial: Mode-Specific Config (.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! šŸŽÆ

Environment Variables and Their Importance

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.

Creating a .env.production file

To create a .env.production file, follow these simple steps:

  1. Navigate to your project's root directory in your terminal.
  2. Create a new file called .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.

Accessing Environment Variables in Vite

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:

javascript
import dotenv from 'dotenv'; dotenv.config();

Now we can access our environment variables using the process.env object:

javascript
console.log(process.env.VITEAPP_API_KEY); console.log(process.env.DATABASE_URL);

Building for Production

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.

Wrapping Up

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.

Quick Quiz
Question 1 of 1

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! šŸŽ‰