Reputation:
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. 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 ?
Upvotes: 1
Views: 8724
Reputation: 4122
The way I do it is using both dotenv and config packages.
You'd create a .env file (which you'll add to .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
In this file you'll add first
require('dotenv').config();
and then you can export js friendly variables
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
import config from 'config';
console.log(config.get('client'));
// { clientId: '1234', clientSecret: 'XXXXX'}
Upvotes: 5
Reputation: 5476
You can use dotenv npm package for this use case
create a .env file in your project something similar to:
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
})
Upvotes: 1