'Can't use dotenv with ES6 modules
I am moving an Express app across from CommonJS require syntax to the ES6 module import syntax. This is fine until I try and use dotenv to load my environment variables and every time I try to access these variables they come back as undefined.
app.js
// importing environmental variables
import dotenv from 'dotenv';
dotenv.config();
import express from 'express';
let x = process.env.David;
console.log(x);
.env
David = test
Solution 1:[1]
Try putting the env config in a separate file and import it first.
// loadEnv.js
import dotenv from 'dotenv';
dotenv.config()
// index.js
import './loadEnv';
import express from 'express';
let x = process.env.David;
console.log(x);
Solution 2:[2]
import "dotenv/config.js";
For .env variables across all files use the above.
Solution 3:[3]
// importing environmental variables
import express from 'express';
import { config } from "dotenv";
config({ path: process.ENV })
let x = process.env.David;
console.log(x);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ozgur Sar |
| Solution 2 | Andrzej Sydor |
| Solution 3 | David hernando Caycedo blum |
