Can't use dotenv with ES6 modules

Viewed 7425

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
3 Answers
import "dotenv/config.js";

For .env variables across all files use the above.

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);
 // importing environmental variables
        import express from 'express';
        import { config } from "dotenv";
        config({ path: process.ENV })
            
        let x = process.env.David;
        console.log(x);
Related