简体   繁体   English

node.js 中的 require('dotenv').config()

[英]require('dotenv').config() in node.js

In my node.js application, I have a require('dotenv').config();在我的 node.js 应用程序中,我有一个require('dotenv').config(); line that I need when developing locally in order to use environment variables.我在本地开发时需要的行以使用环境变量。 When I deploy to AWS however, I need to comment out this line, otherwise the application crashes.但是,当我部署到 AWS 时,我需要注释掉这一行,否则应用程序会崩溃。 Currently I have 4 of these lines and it's a bit annoying to have to keep commenting/uncommenting them when I push/pull the application - is there any workaround for this that removes the need to have to keep removing the line when I deploy to AWS/including the line when I pull and work locally?目前我有 4 行这些行,当我推/拉应用程序时不得不继续注释/取消注释它们有点烦人 - 是否有任何解决方法可以消除在我部署到 AWS 时必须继续删除该行的需要/包括我在本地拉动和工作时的线路?

Maybe you can check the value of NODE_ENV (I assume you deploy in production ).也许您可以检查NODE_ENV的值(我假设您在production部署)。

Something like:就像是:

if (process.env.NODE_ENV === 'development') {
  require('dotenv').config();
}

Or just if NODE_ENV is not production (useful if you have things like NODE_ENV === 'test' ):或者只是如果NODE_ENV不是production (如果你有像NODE_ENV === 'test'这样的东西很有用):

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

Also do take a look at a npm package named config.也请查看名为 config 的 npm 包。 It gives us multiple files.json with default.json, development.json, local.json.它为我们提供了多个 files.json 和 default.json、development.json、local.json。 In some cases, we just need to change some keys in development or any other env while we want something the same in all env like port, jwt secret, etc. Take a look at the link在某些情况下,我们只需要在开发或任何其他环境中更改一些密钥,而我们希望在所有环境中使用相同的东西,如端口、jwt 秘密等。看看链接

https://www.npmjs.com/package/config https://www.npmjs.com/package/config

IMO it is better to not have code that checks the NODE_ENV and loads things for certain cases. IMO 最好没有检查NODE_ENV并在某些情况下加载内容的代码。

I put that to a dedicated npm script like npm run dev where I would load the dotenv/config and set the path for the .env file if needed.我把它放到一个专用的 npm 脚本中,比如npm run dev ,我会在那里加载dotenv/config并在需要时设置.env文件的路径。

In your case the package.json could look like在你的情况下package.json可能看起来像

  "scripts": {
    "dev": "node -r dotenv/config ./src/index.js"
  }

Bonus track: if you have the .env file in the parent folder of your package + enable remote debugger:奖励跟踪:如果您的包的父文件夹中有.env文件+启用远程调试器:

  "scripts": {
    "dev": "DOTENV_CONFIG_PATH=../.env node --inspect=0.0.0.0 -r dotenv/config ./src/index.js"
  }

Then you only run npm run dev and it works.然后你只运行npm run dev就可以了。

For production, I would then add a different npm script without debugger and dotenv/config loading.对于生产,我会添加一个不同的 npm 脚本,而不需要调试器和 dotenv/config 加载。

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

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