Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To load environment variables from a .env file using Vite, follow these steps:

  1. Install the dotenv package by running npm i dotenv in your project's root directory.
  2. Create a .env file in the root directory of your project and add your environment variables in the following format: VARIABLE_NAME=variableValue
  3. In your Vite configuration file (vite.config.js), import the dotenv package at the top of the file: require('dotenv').config().
  4. Access your environment variables inside your Vite configuration file using process.env.VARIABLE_NAME.

Example:

// vite.config.js

require('dotenv').config()

export default {
  mode: 'development',
  port: process.env.PORT || 3000,
  // other vite options
}

Note: Be sure to add the .env file to your .gitignore to keep sensitive data secure.