Full answer
A circular dependency means module A imports B, and B imports A, directly or through other modules. Both systems allow it, but they fail differently.
CommonJS: require runs the module code at the first call and caches its module.exports. If B requires A while A is still running, B gets whatever A has exported so far, which can be an empty object. B keeps a reference to that same object, so properties that A adds later become visible, but only if B reads them later and A did not replace module.exports with a new object. A common bug is module.exports = {...} at the end of A, which leaves B holding the old empty object. Destructuring at load time (const { x } = require('./a')) copies undefined.
ES modules: imports are live, read-only bindings, not copies. Evaluation is depth first: the engine evaluates dependencies before the importing module, and in a cycle, it enters the module that was reached first and does not wait for modules already in progress. So in a cycle, one module runs before its partner has run. The result depends on what you access:
- Function declarations are hoisted and initialized when the module is linked, so calling an imported function works even before its module has run, as long as the function itself does not need uninitialized values.
const,let, andclassexports are in the temporal dead zone until their line runs. Reading one earlier throwsReferenceError.- Reading inside a function that runs later, after all modules have been evaluated, works for everything.
The snippet writes small files to a temporary directory and shows both cases.
How to avoid trouble:
- Remove the cycle: move the shared part into a third module that both import.
- Pass dependencies as arguments, or use dependency injection.
- Access the other module only inside functions, not at the top level.
- Prefer function declarations for exports that other modules need early.
- Use a tool such as
madgeor an ESLint import cycle rule to detect cycles in continuous integration.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { pathToFileURL } = require('node:url');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cycle-'));
const write = (name, text) => fs.writeFileSync(path.join(dir, name), text);
// CommonJS cycle
write('a.cjs', `
exports.early = 'set before requiring b';
const b = require('./b.cjs');
exports.late = 'set after requiring b';
console.log('CJS a done. b saw:', b.sawOfA);
`);
write('b.cjs', `
const a = require('./a.cjs');
exports.sawOfA = Object.keys(a).join(',');
console.log('CJS b done');
`);
// ES module cycle
write('a.mjs', `
import { fromB } from './b.mjs';
export const valueA = 'A';
export function getA() { return valueA; }
console.log('ESM a runs, fromB() ->', fromB());
`);
write('b.mjs', `
import { getA, valueA } from './a.mjs';
export function fromB() { return 'B sees ' + getA(); }
console.log('ESM b runs');
try {
console.log(valueA);
} catch (error) {
console.log('ESM b reading valueA too early:', error.name);
}
`);
require(path.join(dir, 'a.cjs'));
console.log('---');
import(pathToFileURL(path.join(dir, 'a.mjs')).href)
.then(() => {
fs.rmSync(dir, { recursive: true, force: true });
console.log('temporary files removed');
});Run with Node.js v24.22.1 as js-98.js; two runs gave identical output. Output: CJS b done CJS a done. b saw: early --- ESM b runs ESM b reading valueA too early: ReferenceError ESM a runs, fromB() -> B sees A temporary files removed
Key points
- CommonJS returns a partial exports object for a module still loading.
- Replacing module.exports after a cycle leaves the other module with a stale object.
- ES module imports are live bindings; evaluation order in a cycle is depth first.
- Hoisted functions work early; const, let, and class exports throw a ReferenceError before they run.
- Fix by extracting shared code, using late access in functions, and detecting cycles with a tool.
Common mistakes
- Replacing module.exports at the end of a module that takes part in a cycle.
- Destructuring a cyclic CommonJS import at the top level.
- Using const arrow functions as exports that other modules call during evaluation.
- Ignoring cycles because they sometimes work, then getting a different order after a refactor.
Follow-ups
- Why can a hoisted function export be called before its module has run, but a const export cannot?
- How does top-level await change evaluation order in a cycle?
- How would you find import cycles automatically in a large code base?
Tips
- Contrast copies and partial objects in CommonJS with live bindings in ES modules.
- Give the fix first: break the cycle with a shared module.
- Mention tools that detect cycles.