DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Handling Environment Variables in Vite, React, TypeScript Projects!

〜 Properly Differentiate Between Staging and Production Environments 〜

Table of Contents

  1. Introduction
  2. Setting Up Environment Variables
  3. Updating npm scripts
  4. Using Environment Variables in Vite
  5. Ignoring .env Files in Git
  6. Conclusion

Introduction

When managing a project with Vite, React, TypeScript, you'll often need different settings for different environments such as development, staging, and production. In this article, I'll guide you through setting up environment variables specific to each environment.

Setting Up Environment Variables

First, create .env files for each environment at the root of your project:

  • .env.development.local: Set the environment variables for the development environment here.
  • .env.staging.local: Set the environment variables for the staging environment here.
  • .env.production.local: Set the environment variables for the production environment here.

In each file, set environment variables prefixed with VITE_. For example:

VITE_APP_TITLE="My Cool App"
Enter fullscreen mode Exit fullscreen mode

Updating npm scripts

Next, update the scripts section of your package.json:

"scripts": {
    "dev": "vite --mode development & npm run sv",
    "build:staging": "vite build --mode staging",
    "build:prod": "vite build --mode production",
    "vite": "vite",
    "sv": "php -S localhost:8080",
    "lint": "eslint src --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "api:build": "aspida"
}
Enter fullscreen mode Exit fullscreen mode

With this, when you run npm run dev, the .env.development.local file is loaded. When you run npm run build:staging, the .env.staging.local file is loaded. And when you run npm run build:prod, the .env.production.local file is loaded.

Using Environment Variables in Vite

In Vite, you can reference environment variables in your application like import.meta.env.VITE_APP_TITLE. Here is a sample code:

import React from "react";

const AppTitle = () => (
    <h1>{import.meta.env.VITE_APP_TITLE}</h1>
);

export default AppTitle;
Enter fullscreen mode Exit fullscreen mode

Ignoring .env Files in Git

Finally, exclude these .env files from Git versioning. This prevents potential security issues. Add the following line to your .gitignore file:

.env*.local
Enter fullscreen mode Exit fullscreen mode

This excludes all files starting with .env and ending with .local from versioning.

Conclusion

In this article, I explained how to set different environment variables for development, staging, and production environments in Vite, React, TypeScript projects. With this method, you can easily manage different settings for each environment.


Thank you for reading! If you have any questions or comments, feel free to leave them in the comment section below.

Top comments (0)