In a web build, when an ES module imports a CommonJS-only package, what does the bundler emit for that package, and when does its code run?
answer
- exports assigned while it runs
- a function around the body
- run once, then cached
- require calls become wrapper calls
- an unresolved require survives
basics
~20 sA bundler typically wraps the CommonJS module's body in a function that receives exports and module, and emits a small helper that runs it once, on the first require or import, caching module.exports for every later caller.
solid answer
~50 sA CommonJS module builds its exports by assignment while it runs, so its bindings cannot be linked statically the way ES module bindings are. A bundler therefore typically keeps it as a unit: it wraps the body in a function that takes `exports` and `module`, and replaces each `require('./x')` with a literal path by a call to the wrapper for `x`. A runtime helper runs a wrapper the first time it is called and caches `module.exports`, so the body runs once, and lazily: a `require` inside a function body runs only when that function does. An ES module importing it calls the wrapper at its place in evaluation order and passes the result through an interop helper that turns `module.exports` into an object it can bind names from. A `require` the build cannot resolve is left as a call to `require`, which a browser does not define.
code
javascript · 13 lines// isbn.js (CommonJS)
exports.isValid = (s) => s.replace(/-/g, '').length === 13;
// main.js (ES module)
import { isValid } from './isbn.js';
console.log(isValid('978-0-00-000000-0'));
// output a bundler could emit (helper names vary by tool)
var require_isbn = runOnce((exports, module) => {
exports.isValid = (s) => s.replace(/-/g, '').length === 13;
});
var isbn = toNamespace(require_isbn());
console.log(isbn.isValid('978-0-00-000000-0'));go deeper
Recall that CommonJS code is still bundled, kept inside a function, and that it runs once when first required and is cached afterwards.
Explain the parts of the output: the wrapper, the run-once helper, rewritten require calls and the interop step for an ES module importer.
Diagnose a leftover require or a missing server global in a wrapped dependency, and explain how lazy require changes when its code runs.
Weigh accepting CommonJS-only dependencies against the cost of wrapped code in every app, and set a preference for ES module builds where packages offer them.
## Why CommonJS cannot be linked like an ES module An **ES module** declares its imports and exports statically, so a bundler can connect an imported name to the exporting binding before anything runs, and can often concatenate many modules into one scope. A **CommonJS** module does the opposite: it creates its exports by **assignment while it runs** (`exports.parse = …`, `module.exports = …`), and loads its dependencies with `require()`, an ordinary function call that can appear anywhere and runs when it is reached. Which names it exports can depend on run-time branches. The bundler cannot turn that into static bindings without changing behaviour, so current bundlers usually keep the module's own semantics by **wrapping** it. An older approach rewrote CommonJS into ES module syntax and hoisted every `require` to the top, which changed when the code ran; the wrapper avoids that. ## What the bundler emits The code example shows the shape. For each CommonJS module in the graph, output typically contains: 1. **A wrapper function** around the original body, taking `exports` and `module` parameters, so the body's assignments work unchanged. 2. **A run-once helper** that, when first called, creates a `module` object and records it before running the wrapper, then returns the recorded `module.exports` on every later call. This reproduces the module cache that CommonJS relies on. 3. **Rewritten `require` calls.** Each `require('./isbn.js')` with a string literal is resolved at build time like any other specifier and replaced by a call to that module's wrapped function. 4. **An interop step** where an ES module imports a CommonJS one: the importer calls the wrapper and passes `module.exports` through a helper that presents it as an object with named properties and a `default`. Which value `default` receives is the interop rule, a separate subject. Helper names differ from tool to tool; the structure is the same. ## When the code runs | Import site | When the CommonJS body runs | |---|---| | static `import` in an ES module | when the importer is evaluated, at the import's place in the order | | top-level `require()` in CommonJS | when that line runs | | `require()` inside a function | when the function is first called | | second and later `require()` / imports | not again: the cached `module.exports` is returned | The lazy case is the one people get wrong. `const getRules = () => require('./rules.js')` leaves `rules.js` unexecuted until `getRules()` is called, in the bundle just as in the original runtime. Code that relied on a side effect inside `rules.js` happening at startup was never guaranteed it. ## The failure modes - **`require is not defined` in the browser.** A `require` the build did not resolve, because its argument is computed or because the module is marked external, is left as a call to a free `require` variable. Browsers do not define one, so it throws when reached. Resolve the specifier statically, give the browser a real module for it, or import it as an ES module. - **Server globals.** CommonJS code written for a server runtime may read `process`, `__dirname` or built-in server modules. Wrapping does not provide them; the build must replace or stub them, or the code fails at run time. - **Weaker static analysis.** Because the wrapper keeps the module opaque, unused exports of a CommonJS dependency are harder to drop than those of an ES module. How dead code is removed is a separate subject; the point here is that wrapping trades analysis for fidelity. - **Cycles keep CommonJS behaviour.** Because the `module` object is recorded before the body runs, a wrapped module required again while it is still running hands back its partly filled `exports`, as CommonJS itself does; what that means for the code is the import-cycle subject. - **Evaluation order surprises.** A module converted between formats can run earlier or later than before, because ES imports are evaluated before the importer's body while `require` runs inline. ## How to read a wrapped dependency - Search unminified output for the original file name; many tools mark each module with a comment or region marker. - Check that every `require` inside it became a call to another wrapper; a bare `require(` that survives is a candidate for the browser error. - Prefer an ES module build of the dependency when its `exports` map offers one: it skips the wrapper and links statically.
- Why does a bundler wrap a CommonJS module instead of concatenating it into the importer's scope as it can with an ES module?Concatenation needs every exported binding to be known before the code runs, and a CommonJS module only creates its exports by assignment while it runs, sometimes inside branches. It also expects its own `exports` and `module` objects, a module cache, and lazy `require` calls. A run-once wrapper function reproduces all of that without rewriting the module's body, at the price of a little runtime code and weaker static analysis.
- In a bundled browser app, a wrapped CommonJS dependency throws `require is not defined`. How do you find and fix the cause?Search the output for a surviving bare `require(` call; its argument shows the specifier the build did not resolve, typically a computed path or a module marked external. Make the specifier a literal so the build can resolve it, provide a browser module for it, or switch to an ES module build of the dependency. Defining a global `require` only hides the gap.
- A bundler can always list a CommonJS module's exports without running it.
- A wrapped CommonJS module runs again each time it is required.
- A `require` inside a function runs when the bundle first loads.
- Browsers provide `require`, so a leftover call is harmless.
- Wrapping makes unused CommonJS exports easy to remove.