Circular module dependencies
How it works
A cycle exists when a path of imports returns to the starting module. ECMAScript can link cyclic graphs, but a read of an uninitialized lexical export during evaluation can throw ReferenceError. A cycle that only calls a function after initialization may be safe. Prefer extracting shared constants or pure functions into a third module to avoid initialization-order coupling.
Example 1
Save each file separately. Run with Node.js: main.mjs. This is a multi-file example, not a single editor snippet.
a.mjs
import { readA } from "./b.mjs";export const value = 7;export function result() { return readA() + 1; }b.mjs
import { value } from "./a.mjs";export function readA() { return value; }main.mjs
Expected output in the tested environment:
8The cycle links, and the read is delayed until both module bodies have evaluated.
Common mistake
A circular dependency is neither always forbidden nor always safe. The dangerous part here is reading the lexical export too early.
Practice
Move the shared value into shared.mjs and rewrite both dependencies to import it. Draw the resulting acyclic graph.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Circular module dependencies — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
What makes a cyclic ES module graph fail in the early-read case?
Why does the displayed cycle work?
Which redesign can remove the cycle?
Does a successfully linked module graph guarantee successful evaluation?
For Circular module dependencies, what is the console output of example 1 in Node.js 22.16.0?
// File: a.mjsimport { readA } from "./b.mjs";export const value = 7;export function result() { return readA() + 1; }
// File: b.mjsimport { value } from "./a.mjs";export function readA() { return value; }
// File: main.mjsimport { result } from "./a.mjs";console.log(result());