Sub topic 6
ES Modules and CommonJS
This chapter assumes you can write functions and objects in JavaScript, run a file with node, and load a script in a web page with a <script> tag. It covers the two module systems you will meet in practice. You will see how each one loads code, how Node.js decides which one a file uses, and how the two work together. It also covers the errors people hit most often when mixing them.
A module is a file with its own scope. Names declared inside a module stay private unless the module exports them. Other modules can then import those exported names. JavaScript has two module systems:
- ES modules (ESM) are the standard defined in the ECMAScript specification. They use
importandexport, and browsers, Node.js, Deno, and Bun all support them. - CommonJS (CJS) is the system Node.js used before ESM existed. It uses
require()andmodule.exports. Browsers do not support it natively.
The two syntaxes side by side
Here is the same small library written both ways. Node.js treats .mjs files as ES modules and .cjs files as CommonJS, whatever package.json says. That makes these extensions a reliable way to experiment.
// math.mjs
export function add(a, b) {
return a + b;
}
// main.mjs
import { add } from './math.mjs';
console.log(add(2, 3)); // 5// math.cjs
function add(a, b) {
return a + b;
}
module.exports = { add };
// main.cjs
const { add } = require('./math.cjs');
console.log(add(2, 3)); // 5The two versions look nearly the same, but they load code in different ways.
| Aspect | ES modules | CommonJS |
|---|---|---|
| Syntax | `import` / `export` | `require()` / `module.exports` |
| When dependencies are found | Before any code runs (static analysis) | While code runs, each time `require` is called |
| Loading | Asynchronous, in phases | Synchronous, one file at a time |
| Exported values | Live bindings | A copy of what `module.exports` held |
| Strict mode | Always | Only with `'use strict'` |
| Top-level `this` | `undefined` | `module.exports` |
| Top-level `await` | Allowed | Not allowed |
| File location | `import.meta.url`, `import.meta.dirname` | `__filename`, `__dirname` |
| Browser support | Native | None without a bundler |
How ES modules load
An ES module graph loads in three phases:
- Construction. The loader parses the entry file and finds every
importdeclaration without running any code. It fetches those files and repeats until it has found the whole dependency graph. - Linking. Each exported name gets a binding, and each import is connected to the binding it refers to. Imports of names that don't exist fail here, before any code has run.
- Evaluation. Module bodies run, with dependencies before the modules that import them.
Because import declarations are found before evaluation, they have to be static. You can't put import inside an if block or build the module path from a variable. For conditional or computed loading, use dynamic import(), which returns a promise:
// lazy.mjs
const useFast = process.argv.includes('--fast');
const { add } = await import(useFast ? './math.mjs' : './math.mjs');
console.log(add(1, 1));Dynamic import() also works inside CommonJS files. That is the standard way for CommonJS code to load an ES module that uses top-level await.
Live bindings versus copied values
An ES module import gives you a live, read-only view of the exporter's variable. CommonJS gives you whatever value module.exports held when require returned. If you destructure that value, you hold a snapshot.
// counter.mjs
export let count = 0;
export function increment() {
count++;
}
// use-counter.mjs
import { count, increment } from './counter.mjs';
console.log(count); // 0
increment();
console.log(count); // 1, the binding is live
// count = 5; // TypeError: Assignment to constant variable.// counter.cjs
let count = 0;
module.exports = {
count,
increment() {
count++;
},
};
// use-counter.cjs
const { count, increment } = require('./counter.cjs');
console.log(count); // 0
increment();
console.log(count); // still 0, this is a copied numberLive bindings also explain why circular imports between ES modules usually work: a binding fills in once its module evaluates. With CommonJS cycles, one side often sees a partly filled module.exports object.
How Node.js chooses a module system
Node.js decides which module system applies to each file. It goes by the file extension and the nearest package.json above the file:
.mjsis always ESM..cjsis always CommonJS.- For
.js, Node.js finds the nearestpackage.json."type": "module"makes the file ESM, and"type": "commonjs"makes it CommonJS. - If a
.jsfile has no"type"field above it, Node.js treats it as CommonJS. Recent versions (enabled by default from v22.7 and v20.19) also check the syntax: if the file only parses as ESM, because it usesimportorexport, Node.js runs it as ESM.
A project that uses ESM throughout usually declares it once:
{
"name": "my-app",
"version": "1.0.0",
"type": "module"
}ES modules in the browser
Browsers load ES modules from <script type="module">. Module scripts are deferred by default, run in strict mode, and run only once no matter how many times the page imports them. Three rules catch people coming from Node.js:
- Specifiers are URLs.
'./math.js'works.'./math'without the extension fails, because the browser fetches exactly the URL you wrote and does not search for files. - Bare specifiers need an import map.
import { x } from 'lodash-es'fails unless the page has an import map telling the browser whatlodash-espoints to. - Modules need a server. Pages opened with
file://usually can't load modules, because module requests are subject to CORS rules.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="importmap">
{ "imports": { "math": "./math.js" } }
</script>
<script type="module">
import { add } from 'math';
document.body.textContent = `2 + 3 = ${add(2, 3)}`;
</script>
</head>
<body></body>
</html>Serve the folder with any static server, for example npx serve ., and place an ESM math.js next to the page.
Interoperability in Node.js
Many real projects mix the two systems. These are the rules that apply.
ESM importing CommonJS works. The module.exports object becomes the default export. Node.js also tries to detect named exports by static analysis, but it can't always find them:
// main.mjs
import math from './math.cjs'; // always works: module.exports
import { add } from './math.cjs'; // works when Node can detect the name
console.log(math.add(1, 2), add(3, 4));CommonJS requiring ESM used to throw ERR_REQUIRE_ESM. Since v22.12 and v20.19, require() can load an ES module synchronously as long as the module graph has no top-level await. In older versions, or when the graph does use top-level await, use dynamic import():
// main.cjs
(async () => {
const { add } = await import('./math.mjs');
console.log(add(2, 3));
})();CommonJS variables don't exist in ESM. require, module, exports, __filename, and __dirname are not defined in an ES module. Use the ESM equivalents:
// paths.mjs
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
import { createRequire } from 'node:module';
const filename = fileURLToPath(import.meta.url);
const dir = import.meta.dirname ?? dirname(filename); // dirname is Node 20.11+
const require = createRequire(import.meta.url);
console.log(dir);
console.log(require('node:os').platform());Common errors and what they mean
| Error message | Cause | Fix |
|---|---|---|
| `SyntaxError: Cannot use import statement outside a module` | Node.js or the browser loaded the file as a classic script or CommonJS | Use `.mjs`, set `"type": "module"`, or add `type="module"` to the script tag |
| `ReferenceError: require is not defined in ES module scope` | `require` was used in an ESM file | Use `import`, or `createRequire(import.meta.url)` |
| `ReferenceError: __dirname is not defined` | A CommonJS variable was used in ESM | Use `import.meta.dirname` or `fileURLToPath` |
| `ERR_MODULE_NOT_FOUND` for `./utils` | ESM specifiers in Node.js need the file extension | Write `./utils.js` |
| `ERR_REQUIRE_ESM` or `ERR_REQUIRE_ASYNC_MODULE` | `require()` was used on ESM in an older Node.js, or on ESM with top-level await | Use `await import()` |
| `SyntaxError: The requested module does not provide an export named 'x'` | Named import from CJS that Node.js couldn't detect | Import the default export and destructure it |
Choosing between them
For new code, use ES modules. They are the only system browsers run natively, they allow top-level await, and their static structure lets tools remove unused exports (tree-shaking). Choose CommonJS when you maintain an existing CommonJS codebase, or when you depend on tooling that still expects it. If you publish a library, ESM-only is now practical for most audiences, because current Node.js versions can require() synchronous ES modules.
Exercise
A project has package.json with no "type" field, and it is running on Node.js 18. The file app.js contains import fs from 'node:fs';. What happens when you run node app.js, and name two ways to fix it.
Show answer
Node.js 18 has no syntax detection, so it treats app.js as CommonJS and throws "SyntaxError: Cannot use import statement outside a module". To fix it, rename the file to app.mjs, or add "type": "module" to package.json. A third option is to rewrite the import as const fs = require('node:fs');.
Exercise
In ESM, counter.mjs exports let count = 0 and a function increment() that adds one to count. Another module imports both, calls increment() twice, and logs count. What is printed? What would print if both files were CommonJS and the importer destructured { count, increment } from require()?
Show answer
The ESM version prints 2, because the import is a live binding to the exporter's variable. The CommonJS version prints 0, because destructuring copied the number held in module.exports when require returned, and increment changes only the private variable inside counter.cjs.
Exercise
A browser page has <script type="module" src="main.js">, and main.js contains import { add } from './math';. The file math.js exists next to it. Why does this fail, and what is the fix?
Show answer
Browsers resolve module specifiers as URLs and don't add extensions, so the page requests './math', which doesn't exist (a 404). Write import { add } from './math.js';. Another option is an import map that maps a name to ./math.js.