Circular Dependencies and Module Resolution
Two modules importing each other does not always fail, and understanding when it does is the difference between a confusing bug and an obvious one.
Modules are linked before they are evaluated, so bindings exist before values do. A cycle works when each side only uses the other's imports later, and fails with a TDZ error when one reads the other during evaluation. Resolution rules decide what a specifier points at.
EXERCISE
1Why a Cycle Sometimes Works
Loading happens in two phases, and a cycle survives or breaks depending on which phase touches what.
Two modules importing each other sounds like it must fail. Often it does not, and the reason is that loading is not one step.
The two phases:
// 1. LINKING every module in the graph is parsed, and its imports
// and exports are wired together. No code has run yet.
// Bindings exist; they hold nothing.
//
// 2. EVALUATION modules run, depth first, in import order.
// Bindings receive their values as each line executes.
Because linking comes first, a module can hold a reference to something that does not have a value yet. That is exactly what makes some cycles work.
A cycle that works, because the use is deferred:
// a.js
import { bHelper } from "./b.js";
export function aHelper() {
return `a calls ${bHelper()}`;
}
// b.js
import { aHelper } from "./a.js";
export function bHelper() {
return "b";
}
export function callBoth() {
return aHelper();
}
Neither module calls the other while it is being evaluated. By the time anything runs, both are fully initialised. Function declarations are hoisted, so even the order does not matter.
A cycle that breaks, because the use is immediate:
// a.js
import { bValue } from "./b.js";
export const aValue = `a sees ${bValue}`; // reads b during evaluation
// b.js
import { aValue } from "./a.js";
export const bValue = `b sees ${aValue}`; // reads a during evaluation
// ReferenceError: Cannot access 'bValue' before initialization
That error is the Temporal Dead Zone from the foundations course, appearing across module boundaries. The binding exists, because linking created it. It has no value, because b.js has not run its line yet.
The rule, stated once:
// A cycle is fine when each module only USES the other's imports
// inside a function, called later.
//
// A cycle breaks when a module READS the other's import at the
// top level, during evaluation.
And the usual fix is not to break the cycle cleverly:
// Extract what both need into a third module that imports neither.
//
// shared.js <-- a.js
// <-- b.js
//
// The cycle disappears rather than being worked around.
A cycle that currently works is fragile. Someone moves a call from inside a function to the top level, and a module three files away starts throwing. The extraction is worth doing even when nothing is broken yet.
Pro Tip: Treat a circular import as a design signal rather than a technical problem to solve. It means two modules each know something about the other, and the shared thing almost always wants its own file. Bundlers and linters can warn you about cycles; turning that warning on is cheap and the fix is usually ten minutes.
EXERCISE
2What a Specifier Points At
The string in an import has rules behind it, and they differ between the browser and Node.
Three kinds of specifier:
import { a } from "./utils.js"; // relative: from this file
import { b } from "/src/utils.js"; // absolute: from the site root
import { c } from "lodash"; // bare: a package name
In the browser, the path must be real and complete:
// Works
import { a } from "./utils.js";
// Fails: the browser does not guess extensions
// import { a } from "./utils";
// Failed to resolve module specifier
// Fails: the browser has no node_modules
// import _ from "lodash";
A browser resolves a specifier as a URL, nothing more. The extension is required and bare names mean nothing, unless you tell it what they mean:
<script type="importmap">
{ "imports": { "lodash": "https://cdn.example.com/lodash.js" } }
</script>
An import map is how bare specifiers work without a bundler. Most projects use a bundler instead, which rewrites them at build time.
In Node, the rules differ by file type:
// In an ES module, the extension is required, as in the browser:
import { a } from "./utils.js";
// In CommonJS, it never was:
const { a } = require("./utils"); // finds utils.js, utils/index.js
That asymmetry is the source of a large share of the friction in migrating a project, because code that worked for a decade suddenly needs extensions everywhere.
How Node decides which one a file is:
// package.json
{ "type": "module" } // .js files are ES modules
{ "type": "commonjs" } // .js files are CommonJS (the default)
// Or by extension, which always wins:
// .mjs always an ES module
// .cjs always CommonJS
And the interop, which is not symmetrical:
// ESM can import CommonJS. The whole module.exports becomes the default.
import pkg from "./legacy.cjs";
const { helper } = pkg;
// CommonJS cannot require ESM. It is asynchronous, and require is not.
// const { a } = require("./modern.mjs"); // ERR_REQUIRE_ESM
//
// Use dynamic import, which returns a promise:
const { a } = await import("./modern.mjs");
Recent Node versions relax this for modules with no top-level await, but writing code that assumes the relaxation is a portability risk.
A resolution order worth knowing for packages:
// package.json of a library
{
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
}
}
The exports field lets one package ship both formats and lets the resolver pick. It also makes everything not listed genuinely private, which the older main field never did.
Pro Tip: Write the file extension in every relative import, even in Node where a bundler would let you omit it. It is required by the browser and by Node's ESM loader, it costs three characters, and it removes an entire class of "works in one place and not the other" that is tedious to debug.
EXERCISE
3Designing a Module's Surface
What a module exports, and what it does when merely imported, are design decisions with consequences for everyone importing it.
Everything so far was mechanics. This is the part that decides whether a codebase stays workable.
Side effects at module scope run whether or not anyone wanted them:
// analytics.js
const tracker = createTracker();
tracker.start(); // runs on import, always
export { tracker };
Anyone importing tracker, including a test that only wants to inspect it, starts the tracker. The import graph now decides when tracking begins, and nobody reading the importing file can see that.
The fix is to export the capability rather than perform the action:
// analytics.js
let tracker = null;
export function startTracking() {
tracker = createTracker();
tracker.start();
return tracker;
}
Now the caller decides, and the decision is visible at the call site.
Export the narrowest thing that works:
// Leaky: the internal array is reachable and mutable
export const cache = new Map();
// Controlled: callers get behaviour, not the container
const cache = new Map();
export function get(key) {
return cache.get(key);
}
export function set(key, value) {
cache.set(key, value);
return value;
}
A module has no #private, but not exporting something is exactly as effective. Anything you export becomes something you must keep working.
Avoid deep import paths into other modules:
// Fragile: reaching into another module's internals
import { helper } from "../user/internal/helpers/format.js";
// Stable: importing the surface it chose to offer
import { formatName } from "../user/index.js";
The first version breaks when that folder is reorganised. The exports field in a package's package.json exists to make this impossible for published libraries, and the same discipline is worth applying inside one codebase.
And a shape that quietly causes trouble:
// utils.js, a file that accumulates everything
export function formatDate() { /* ... */ }
export function parseCsv() { /* ... */ }
export function debounce() { /* ... */ }
export function validateEmail() { /* ... */ }
Nothing here is wrong in isolation. The problem is that every file importing one function now depends on a module that imports whatever all four of those need, and the dependency graph grows edges that mean nothing. A file named for what it contains, such as date.js or csv.js, keeps the graph honest.
Pro Tip: The question to ask of any export is whether you are willing to keep it working. Everything exported is a promise to some other file, and unexporting something later is a breaking change even inside a single codebase. Start narrow; widening is easy and cheap, and narrowing never is.
