debugModeratepending
Circular dependencies causing undefined imports
Viewed 0 times
circular dependencyundefined importmadgeimport cyclemodule initialization
nodejsbrowser
Error Messages
Problem
Imported value is undefined at runtime even though the export exists. The module loads without errors but the imported value is undefined when accessed. Only happens with certain import orders.
Solution
(1) Check for circular dependencies: A imports B, B imports A. Use madge or eslint-plugin-import to detect cycles. (2) How it happens: when A loads, it starts executing. Midway, it imports B. B imports A, but A hasn't finished executing yet — so B gets A's partially-initialized exports (undefined). (3) Fixes: extract shared code into a third module C that both A and B import. (4) Use lazy imports: import inside the function that needs it, not at module top level. (5) Restructure: if A and B always need each other, they should probably be one module. (6) ESM handles cycles better than CJS but the problem can still occur with class/function hoisting differences.
Why
Module systems execute modules on first import and cache the result. During circular imports, one module gets the other's incomplete exports because it hasn't finished initializing yet.
Revisions (0)
No revisions yet.