Sub topic 6
ES Modules and CommonJS
This chapter assumes you can run a script with node and load a script in a web page, which the previous chapters covered. It also assumes you know basic JavaScript functions and objects.
A module is a file with its own scope. Its variables stay private unless the file exports them. JavaScript has two module systems. ES modules (ESM) are the language standard, and both browsers and Node.js support them. CommonJS (CJS) is the older system that Node.js created before ESM existed. Many npm packages still use it.
ES modules
ESM uses the export and import keywords. The engine reads these statements before it runs any code, so it knows the whole dependency graph in advance.
// math.mjs
export function add(a, b) {
return a + b;
}// main.mjs
import { add } from './math.mjs';
console.log(add(2, 3)); // 5Run it with node main.mjs. In a browser, load the entry file with <script type="module" src="main.mjs"></script>. In both places, write relative paths with ./ and include the file extension. ESM does not try missing extensions for you.
ES modules also run in strict mode automatically, and they support top-level await.
CommonJS
CommonJS uses a plain object called module.exports and a function called require. require loads the file synchronously and returns whatever that file exported.
// math.cjs
function add(a, b) {
return a + b;
}
module.exports = { add };// main.cjs
const { add } = require('./math.cjs');
console.log(add(2, 3)); // 5Browsers do not support CommonJS. Browser code written in CommonJS has to go through a bundler first.
How Node.js chooses
Node.js picks the module system for each file separately, using these rules:
| File | Treated as |
|---|---|
| `.mjs` | ES module |
| `.cjs` | CommonJS |
| `.js` with `"type": "module"` in the nearest `package.json` | ES module |
| `.js` with `"type": "commonjs"` or no `type` field | CommonJS (recent versions also detect ESM syntax) |
{
"name": "demo",
"type": "module"
}Mixing the two
An ES module can import a CommonJS file. Node.js exposes module.exports as the default export:
// use-cjs.mjs
import math from './math.cjs';
console.log(math.add(1, 1)); // 2Going the other way has more limits. A CommonJS file can always load ESM with dynamic import(), which returns a promise. Node.js 22 and later also let require load an ES module, as long as that module does not use top-level await.
Common errors
| Error message | Cause | Fix |
|---|---|---|
| `Cannot use import statement outside a module` | A `.js` file uses `import`, but Node.js treats it as CommonJS | Rename the file to `.mjs` or set `"type": "module"` |
| `require is not defined in ES module scope` | `require` is called inside an ES module | Use `import`, or `createRequire` from `node:module` |
| `__dirname is not defined` | CommonJS-only variables are used in ESM | Use `import.meta.dirname` (Node.js 20.11+) or `new URL('.', import.meta.url)` |
| `ERR_MODULE_NOT_FOUND` for `./math` | The extension is missing in an ESM import | Write `./math.js` |
Exercise
A project's package.json has no "type" field. The file app.js contains import fs from 'node:fs'; and fails with "Cannot use import statement outside a module" on your Node.js version. Name two different ways to fix it.
Show answer
Rename the file to app.mjs so Node.js treats it as an ES module, or add "type": "module" to package.json so every .js file in the package is treated as ESM. A third option is to rewrite the import as const fs = require('node:fs'); and keep the file as CommonJS.
Exercise
In main.cjs, const m = require('./lib.mjs'); throws an error, and lib.mjs uses top-level await. Why does it fail, and how can main.cjs load lib.mjs?
Show answer
require is synchronous, so it cannot load a module whose evaluation waits on top-level await. Use dynamic import instead: import('./lib.mjs').then((m) => { /* use m */ });.