Sub topic 16
Circular Dependencies and How to Untangle Them
This chapter assumes you have read the earlier chapter on how modules are linked and evaluated. It also assumes you know how let and const behave before their declaration runs. You can follow along in Node.js with a package.json that sets "type": "module", or by using .mjs files.
A circular dependency happens when module A imports module B and module B, directly or through other modules, imports module A. ES modules allow this, and many cycles cause no problems. A cycle only breaks when one module reads a binding that the other module has not initialized yet. This chapter explains when that happens, how to recognize the error, and how to restructure code so the problem goes away.
Why Cycles Are Allowed at All
Linking happens before evaluation. During linking, the engine creates every module's bindings and connects each import to its matching export. Because the connections are live bindings and not copied values, a cycle in the import graph is not a contradiction: each module just points at the other's variables.
The trouble starts at evaluation time. Code has to run in some order, and in a cycle at least one module runs before a module it depends on has finished.
How Evaluation Order Works in a Cycle
The engine walks the import graph depth-first, starting from the entry point. A module evaluates after all of its dependencies have evaluated. When the walk reaches a module that is already in progress, it does not start that module again. It treats the module as handled and carries on.
Take this pair of files:
// a.js
import { b } from './b.js';
export const a = 'A';
console.log(b);
// b.js
import { a } from './a.js';
export const b = 'B';
console.log(a); // ReferenceError when a.js is the entry point: a is not yet initializedRun node a.js and the steps go like this:
- The engine starts
a.jsand sees that it depends onb.js. - It starts
b.jsand sees that it depends ona.js. Sincea.jsis already in progress, the engine skips it. b.jshas no other dependencies, so it evaluates first. It setsbto'B'and then readsa.- The
const a = 'A'line ina.jshas not run yet, soais still in its temporal dead zone (TDZ). The TDZ is the period between creating alet,const, orclassbinding and running its declaration. Reading the binding during that period throws.
Node.js reports the failure like this:
ReferenceError: Cannot access 'a' before initialization
at file:///project/b.js:3:13If you see that message and the name belongs to an imported binding, look for a cycle.
Cycles That Work
A cycle is safe when no module reads an uninitialized binding during its own top-level evaluation. There are two common ways code ends up in that situation.
Access Deferred Into a Function
If a binding is only read inside a function, the read happens when the function is called, not when the module evaluates.
// a.js
import { describeB } from './b.js';
export const a = 'A';
console.log(describeB()); // "b sees A"
// b.js
import { a } from './a.js';
export const b = 'B';
export function describeB() {
return `b sees ${a}`;
}b.js still evaluates first, but it only defines b and describeB and never reads a. Then a.js initializes a and calls describeB(). By that point a holds a value.
Function Declarations Are Initialized During Linking
Function declarations are created and assigned during linking, before any module code runs. A module in a cycle can therefore call an imported function declaration at top level:
// a.js
import './b.js';
export function helper() {
return 'helped';
}
// b.js
import { helper } from './a.js';
console.log(helper()); // "helped", even though a.js has not evaluatedChange helper to export const helper = () => 'helped'; and the same code throws, because arrow functions assigned to const are subject to the TDZ. This difference is why some cycles break after what looks like a harmless refactor from function to an arrow function.
Common Sources of Cycles
- Barrel modules. A file imports from
./index.jswhileindex.jsre-exports that same file. Internal modules should import from each other's files directly, and only outside code should use the barrel. - Two-way model relationships.
user.jsimportsorder.jsfor type checks or factories, andorder.jsimportsuser.jsfor the same reason. - Shared constants placed in a high-level module. A low-level utility imports a constant from the app's main module, and the main module imports the utility.
Untangling a Cycle
| Fix | When to use it | Trade-off |
|---|---|---|
| Extract shared code into a third module | Both modules need the same values or helpers | Adds a file, but removes the cycle entirely |
| Move reads inside functions | Values are only needed at call time | The cycle stays and can break again if someone adds a top-level read |
| Use function declarations | A top-level call to an imported function is required | Relies on a subtle rule that later edits can undo |
| Pass dependencies as arguments | One module only needs the other at runtime | Callers must supply the dependency |
| Use dynamic `import()` | The dependency is needed rarely, inside async code | Makes the call asynchronous |
Extracting shared code is usually the right fix, because the import graph becomes a tree again. Here is the broken example from earlier, restructured:
// constants.js
export const a = 'A';
export const b = 'B';
// a.js
import { a, b } from './constants.js';
console.log(a, b); // "A B"
// b.js
import { a, b } from './constants.js';
console.log(a, b); // "A B"constants.js has no imports, so it always evaluates first, and both modules see initialized values whichever one is the entry point.
Passing dependencies as arguments, often called dependency injection, also breaks the import edge:
// format.js
export function formatOrder(order, formatUser) {
return `Order ${order.id} for ${formatUser(order.user)}`;
}
// user.js
import { formatOrder } from './format.js';
export function formatUser(user) {
return user.name;
}
console.log(formatOrder({ id: 7, user: { name: 'Ada' } }, formatUser));
// "Order 7 for Ada"format.js never imports user.js, so there is no cycle.
Finding Cycles Before They Bite
Small projects let you spot cycles by reading the imports. Larger ones need a tool. The madge package prints every cycle in a directory:
npx madge --circular --extensions js src/Bundlers such as Rollup also warn about circular dependencies during a build. Treat these warnings as tasks to fix, not noise. A cycle that works today is still fragile: it depends on the entry point, on statement order, and on whether exports are declarations or const bindings.
Exercise
In the first example, a.js is the entry point and b.js reads a at top level. If you swap the two console.log lines so that b.js logs b and a.js logs a, does the program still throw? What does it print?
Show answer
It no longer throws. b.js evaluates first and logs "B", which it has just initialized. Then a.js initializes a and logs "A". No module reads the other's binding at top level, so the TDZ never comes into play even though the cycle is still there.
Exercise
A module config.js contains export const getConfig = () => settings; and is part of a cycle. Another module in the cycle calls getConfig() at top level and gets "Cannot access 'getConfig' before initialization". Name two ways to fix it and say which one is more durable.
Show answer
You can turn it into a function declaration, export function getConfig() { return settings; }, which is initialized during linking (though settings itself must also be initialized by the time the function is called). You can also move the shared state into a separate module that neither module in the cycle depends on through the other. Extracting the module is more durable because it removes the cycle, while the function declaration fix depends on a subtle rule that a later refactor can undo.