简体   繁体   中英

How to use different environments with `.env` files in NodeJs

I am currently building a backend in nodejs. I am thinking about how to add an environment configuration to the project. My idea is that I have a /config folder in which I have my envparser.ts (have to think about a better name for this ^^) which interprets my .env files to use them as regular javascript const. By using scripts in my package.json I would like to have the ability to switch the envs. But I don´t know how to switch between multiple .env files using dotenv.

File structure:

config/
   .env.development
   .env.production
   envparser.ts

Scripts:

 yarn start yarn start -p/-production //Or a different Syntax to change envs

You can use dotenv package for accessing ur .env.* files.


You can switch between different environments by changing the NODE_ENV variable using the different started commands in package.json

For eg:

"scripts": {
    "start": "NODE_ENV=development nodemon index.js",
    "deploy": "NODE_ENV=production node index.js"
}

And then, u can access them in your index.js file as:

require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })

You can have something like this in your scripts section in package.json

"start:dev": "node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env.development", 
"start:prod": "node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env.production"

start server in DEV mode by running npm run start:dev

start server in PROD mode by running npm run start:prod

You can have something like this in your scripts section in package.json

"dev": "nodemon -r dotenv/config index.js"

https://i.stack.imgur.com/5Umge.png

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM