简体   繁体   English

如何在 NodeJs 中使用带有 .env 文件的不同环境

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

I am currently building a backend in nodejs.我目前正在用 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.我的想法是我有一个/config文件夹,其中有我的envparser.ts (必须为此考虑一个更好的名称 ^^),它解释我的.env文件以将它们用作常规 javascript const。 By using scripts in my package.json I would like to have the ability to switch the envs.通过在我的package.json中使用脚本,我希望能够切换环境。 But I don´t know how to switch between multiple .env files using dotenv.但我不知道如何使用 dotenv 在多个.env文件之间切换。

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.您可以使用dotenv package 访问您的.env.*文件。


You can switch between different environments by changing the NODE_ENV variable using the different started commands in package.json您可以使用 package.json 中的不同启动命令更改NODE_ENV变量来在不同环境之间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:然后,你可以在你的 index.js 文件中访问它们:

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

You can have something like this in your scripts section in package.json您可以在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通过运行npm run start:devDEV模式启动服务器

start server in PROD mode by running npm run start:prod通过运行npm run start:prodPROD模式启动服务器

You can have something like this in your scripts section in package.json您可以在 package.json 的脚本部分中使用类似的内容

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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