Ask Your Question
2

What is the method for loading environment variables from a .env file using Vite?

asked 2022-03-20 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-01-19 05:00:00 +0000

bukephalos gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-03-20 11:00:00 +0000

Seen: 15 times

Last updated: Jan 19 '22