简体   繁体   English

在 nodejs 应用程序中如何使用 dotenv 和 config?

[英]in nodejs app how to use dotenv and config?

I am new to development, i understand that dotenv create environment variables that we don't want to expose in our code , while config create similar variables to be used by app for configuration however I am little confused about use case.我是开发新手,我知道 dotenv 创建了我们不想在我们的代码中公开的环境变量,而 config 创建了类似的变量以供应用程序用于配置,但是我对用例并不感到困惑。 could you explain it a little or point me to further resource for better understanding.你能解释一下吗,或者给我指出进一步的资源以便更好地理解。 and is there any other similar packages that create environment variables and how are they used ?是否还有其他类似的包可以创建环境变量以及它们是如何使用的?

You can use dotenv npm package for this use case您可以在此用例中使用dotenv npm 包

create a .env file in your project something similar to:在您的项目中创建一个类似于以下内容的 .env 文件:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

then you can configure your file:然后你可以配置你的文件:

const dotenv = require('dotenv');
dotenv.config({ path: path.resolve(__dirname, './config.env') })

then you can use them like:那么你可以像这样使用它们:

db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

The way I do it is using both dotenv and config packages.我这样做的方式是同时使用dotenvconfig包。

You'd create a .env file (which you'll add to .gitignore)您将创建一个 .env 文件(您将添加到 .gitignore)

For example例如

client_id='1234'
client_secret='XXXXX'

Then you create a folder called config at the root of your project, and inside it a file default.js然后在项目的根目录下创建一个名为 config 的文件夹,并在其中创建一个文件default.js

In this file you'll add first在此文件中,您将首先添加

require('dotenv').config();

and then you can export js friendly variables然后你可以导出js友好的变量

require('dotenv').config(); 

export const client = {
    clientId: process.env.client_id,
    clientSecret: process.env.client_secret
}

Finally you can use these in your index.ts for example最后,您可以在 index.ts 中使用这些,例如

import config from 'config';

console.log(config.get('client'));
// { clientId: '1234', clientSecret: 'XXXXX'}

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

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