nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨

Home Page:https://nodejs.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Issue with loadEnvFile in ESM

EvilG-MC opened this issue · comments

Version

v20.13.1

Platform

Microsoft Windows NT 10.0.22631.0 x64

Subsystem

No response

What steps will reproduce the bug?

Using ESM and a class, loading variables from the .env works in a strange way.

  1. Create a .cjs file (Ex: index.cjs) and add this:
console.info("Executed from CJS.");
process.loadEnvFile();

const MyClass = require("./class");

new MyClass();
  1. Create a .mjs file. (Ex: index.mjs) and add this:
console.info("Executed from ESM.");
process.loadEnvFile();

import MyClass from "./class.js";

new MyClass();
  1. Create a .env with this content:
A = a
B = b
C = c
  1. Finally create a class and export it (Ex: class.js) and add this:
console.log({
    A: process.env.A,
    B: process.env.B,
    C: process.env.C,
})

module.exports = class MyClass {};

And running the index.mjs file should give the following output:

node .\index.mjs

{ A: undefined, B: undefined, C: undefined }
Executed from ESM.

And if you run the index.cjs file it should give the following output:

node .\index.cjs

Executed from CJS.
{ A: 'a', B: 'b', C: 'c' }

How often does it reproduce? Is there a required condition?

No response

What is the expected behavior? Why is that the expected behavior?

node .\index.mjs

Executed from ESM.
{ A: 'a', B: 'b', C: 'c' }

What do you see instead?

node .\index.mjs

{ A: undefined, B: undefined, C: undefined }
Executed from ESM.

Additional information

No response

this is an expected behavior: see import hoisting: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#hoisting

a solution can be to await import("./class.js")