If you would like to call dotenv
only once in the entire application,
as was possible in commonjs
with require
.
In particular, in case you want to change the config, such as changing the PATH like this:
config({ path: '../.env' })
You must write a separate file, like this:
// env.js
import dotenv from 'dotenv';
dotenv.config({ path: '../.env' });
Then import the env.js
file in the main file like this:
// index.js
/** Import first before calling other files */
import './env.js';
import sqlConnect from './sql'
import express from 'express';
const PORT = process.env.PORT;
app.listen(PORT,()=>{
console.log(`listening on port ${PORT}`);
})
Note!
Import first before calling other files in the application.
Since in ES6 the import
is performed before the code is executed.
You can see more here:
https://hacks.mozilla.org/2015/08/es6-in-depth-modules/
source:
https://www.npmjs.com/package/dotenv#how-do-i-use-dotenv-with-import