我应该在每个节点JS文件中调用dotenv吗? [英] Should I call dotenv in every node JS file?

查看:51
本文介绍了我应该在每个节点JS文件中调用dotenv吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用环境变量.不幸的是,我是一个没有经验的开发人员,所以很晚才决定在我的项目中实施这样的解决方案.

I want to work with environment variables. Unfortunately, I am an inexperienced developer and decided very late to implement such a solution in my project.

我正在尝试将位于.env文件中的环境变量注入所有JS文件(并非所有的JS文件都使用环境变量,但我认为这样会更快,更容易).目前,我正在使用dotenv软件包,但显然它可以一次处理一个文件.

I'm trying to inject environment variables, located in .env file, to all JS files (not all of them using environment variables, but I thought it would be faster and easier). Currently, I'm using dotenv package but it is obviously working in one file at once.

我应该以标准方式使用dotenv吗?也许有一个我不知道的漏洞,这就是为什么以这种方式使用环境变量非常不受欢迎.

Should I use dotenv the standard way? Maybe there's a vulnerability I don't know of and that's why it is very unpopular to use environment variables this way.

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

推荐答案

就像提到的文件注释一样,您应该为ENV提供一个入口点.您不想在每个文件中都 require('dotenv').

Like the comment on your file mentioned, you should have an entry point for your ENVs. You don't want to require('dotenv') in every file.

相反,请在utils或core文件夹中创建一个新文件(命名为 environment.js 之类的文件).

Instead, create a new file (named something like environment.js) that is in the utils or core folder.

require('dotenv').config();

/* eslint no-process-env:0 */
module.exports.default = {

    env: process.env.env,
    url: process.env.url,
    apiUrl: process.env.apiUrl,
    logLevel: process.env.logLevel,

    db: {
        host: process.env.db_host
        port: process.env.db_port
    }
    // Grab everything in you .env file here
}

然后在其他每个文件中,您都可以将配置包含在漂亮的json对象中.

Then in each of your other files you can include your configs in a nice json object.

const config = require('../utils/environment');

dbConnector(config.db.host, config.db.port);
// blah blah blah

这篇关于我应该在每个节点JS文件中调用dotenv吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆