Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 249
David Mulholland Avatar asked Oct 31 '20 10:10

David Mulholland


People also ask

Can I use dotenv in frontend?

Dotenv is wonderful. It allows you to use environment variables in your code, hence separating the code from its running environment. The problem I have with it is that it is common to see people using it in the front-end of their web application (served static files, non-SSR applications).

Can not find module dotenv?

To solve the error "Cannot find module 'dotenv'", make sure to install the dotenv package by opening your terminal in your project's root directory and running the following command: npm install dotenv and restart your IDE and development server.

How do I use dotenv packages?

To use DotEnv, first install it using the command: npm i dotenv . Then in your app, require and configure the package like this: require('dotenv'). config() .


2 Answers

import "dotenv/config.js";

For .env variables across all files use the above.

like image 102
Priyanshu Gupta Avatar answered Sep 18 '22 12:09

Priyanshu Gupta


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);
like image 41
Ozgur Sar Avatar answered Sep 19 '22 12:09

Ozgur Sar