CS Fundamentals Trainer · Guides
JavaScript modules: ES modules, CommonJS and what bundlers actually do
The difference between import/export (ES modules) and require/module.exports (CommonJS): live bindings against copied values, static against dynamic loading, how Node decides which one a file is, top-level await, dynamic import(), tree shaking, circular imports and what a bundler adds - with outputs produced by running the code in Node 22.
4 min read
A JavaScript program is rarely one file. Two module systems exist side by side: CommonJS (CJS), born in Node.js, and ES modules (ESM), the language standard since ES2015. Most "cannot use import statement outside a module" and "require is not defined" errors come from mixing them without knowing which one a file is.
The two syntaxes
| CommonJS | ES modules | |
|---|---|---|
| Import | const x = require('./x') | import x from './x.js' |
| Export | module.exports = … / exports.a = … | export const a = … / export default … |
| Loading | synchronous, at run time, require is a function | static syntax, analysed before running |
| Strict mode | no, unless you ask | always |
__dirname, require | available | not available (use import.meta.url) |
Top-level await | no | yes |
Live bindings against copied values
An ES module exports bindings, not values: importers see later changes, and cannot assign to them.
// lib.mjs
export let count = 0;
export function inc() { count++; }
// use.mjs
import { count, inc } from './lib.mjs';
console.log(count); inc(); console.log(count); // 0 then 1
count = 5; // TypeError: assignment to constant
A CommonJS export is an ordinary object property, so module.exports = { count, inc } copies the value of count when the module runs. After inc() the importer still sees 0 (run it: 0, 0). Read through the object (lib.count) or export a getter if you need a live value.
How Node picks the system
.mjsis ESM and.cjsis CJS, whatever else is configured.- For
.js, the nearestpackage.jsondecides:"type": "module"makes it ESM; otherwise (or"type": "commonjs") it is CJS. - In ESM, relative imports need the file extension (
./lib.js), and a directory import does not resolve toindex.js. Bundlers and TypeScript often relax this, Node does not.
Mixing them
- ESM can import CJS:
import lib from './lib.cjs'givesmodule.exportsas the default export (named imports work only when Node can detect them). - CJS can load ESM with dynamic
import(), which returns a promise and works in both systems:import('./lib.mjs').then(m => m.default()). Since Node 22.12,require()can also load an ES module if it contains no top-levelawait; on older versions it throwsERR_REQUIRE_ESM. - A file that is ESM has no
require,moduleor__dirname. Runningtypeof requirethere givesundefined. Useimport.meta.urlandfileURLToPathinstead.
Top-level await and dynamic import
ESM allows await at the top level: const data = await fetch(url).then(r => r.json());. The module's importers wait for it. Use it sparingly, because a slow top-level await delays everything that imports the module.
import('./x.js') is how you lazy-load code: the browser (or Node) fetches and evaluates the module only when it runs. The result is a namespace object (m.default, m.count, …).
Circular imports
A imports B and B imports A. ESM handles this because bindings are resolved before code runs, but a binding is in its temporal dead zone until its module has been evaluated, so touching it too early throws ReferenceError. CJS returns whatever the other module has exported so far, often an empty object. In both systems the fix is the same: move the shared code into a third module that depends on neither.
What a bundler does
Browsers can load ESM natively, but a real application is hundreds of modules, and each one costs a request, so tools (Vite, esbuild, webpack, Rollup) bundle them. They also:
- Tree-shake: because
import/exportare static, unused exports can be dropped. This works much worse with CJS (dynamicrequire) and with modules that have side effects, so libraries mark themselves with"sideEffects": falseinpackage.json. - Split code at dynamic
import()calls into separate chunks. - Transform TypeScript, JSX and newer syntax, and minify the output.
- Resolve bare specifiers such as
import 'react'to files innode_modules. A browser cannot do that by itself, unless you use an import map.
Practical rules
- New code: write ESM, set
"type": "module"and use explicit extensions where Node runs it directly. - Do not rely on mutable exports; export functions that return the current value, or objects you mutate.
- Import what you use (
import { map } from 'lodash-es'), not whole libraries, so tree shaking can help. - Keep modules free of side effects at import time, other than clearly named "setup" modules.
Sources
- Node.js: Modules: ECMAScript modules — resolution,
type,import.meta, interoperability. - Node.js: Modules: CommonJS modules.
- MDN: JavaScript modules.
Practise this topic: JavaScript