Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Node.js ESM vs CommonJS: import, require, and package.json exports

"type" decides how a .js file loads, and the exports field decides what a package exposes. Missing extensions, __dirname, and dual-package state are the usual failures.

~4 min readNode.js
#Node.js#ESM#CommonJS#Modules
3D illustration of two gates labelled with import and require lanes beside a package json panel

Quick Summary

Node.js loads JavaScript as either CommonJS or ES modules, and the file extension plus the nearest package.json "type" field decide which. .mjs is always ESM, .cjs is always CommonJS, and .js follows "type": "module" or "type": "commonjs" (default).

The two systems differ in more than syntax. ESM is resolved and linked before any code runs, which is what enables live bindings and top-level await; CommonJS resolves at call time, which is what allows require() inside an if. ESM has no require, no __dirname, no extension guessing, and no NODE_PATH.

The exports field in package.json is where the two meet. It declares which subpaths a package exposes and which file each condition (import, require, node, default) resolves to. Adding it is also a breaking change: every path not listed becomes private.

Basic Syntax and Core Signatures

json
{ "name": "my-lib", "type": "module", "main": "./dist/index.cjs", "module": "./dist/index.js", "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js", "require": "./dist/index.cjs", "default": "./dist/index.js" }, "./utils": { "import": "./dist/utils.js", "require": "./dist/utils.cjs" }, "./package.json": "./package.json", "./internal/*": null } }
js
// ESM import fs from 'node:fs'; // built-in, node: prefix recommended import { readFile } from 'node:fs/promises'; import pkg from './package.json' with { type: 'json' }; // import attributes const url = import.meta.url; const dir = import.meta.dirname; // Node 20.11+ const here = new URL('./data.csv', import.meta.url); // CommonJS equivalents const fs = require('node:fs'); const { readFile } = require('node:fs/promises'); const pkg = require('./package.json'); // plain require, no attributes const dir = __dirname; const self = require.resolve('./data.csv');
js
// Bridging in both directions import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); // CJS API inside ESM const legacy = require('legacy-pkg'); // ESM from CJS: Node 22.12+ and 20.19+, when the module graph is synchronous const esm = require('./esm-only.mjs'); // no top-level await inside

Key Comparison Table

FeatureCommonJSES modules
Statementrequire(), module.exportsimport, export
Resolution timeAt callBefore evaluation, statically
__dirname / __filenameAvailableimport.meta.dirname / .filename
Extension in specifierOptional, guessedRequired
Directory index.jsResolved automaticallyNot resolved
NODE_PATHHonouredIgnored
Top-level awaitNot allowedAllowed
this at top levelmodule.exportsundefined
BindingsCopied valuesLive, read-only
Strict modeOpt-inAlways
JSON importrequire('./x.json')with { type: 'json' }
Condition key in exportsChosen whenOrder rule
typesTypeScript resolutionFirst, or types are missed
nodeAny Node.js runtimeBefore default
importimport statement or import()Before require
requirerequire() callAfter import
browserBundlers targeting browsersTool-specific
defaultNothing else matchedAlways last

Practical Edge Cases and Deep Dives

1. __dirname is not defined

js
// ESM: TypeError: __dirname is not defined import { fileURLToPath } from 'node:url'; import path from 'node:path'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // or, Node 20.11+ / 21.2+: const dir = import.meta.dirname;

The error appears the moment a project switches "type": "module", because half the ecosystem's examples use __dirname to locate templates, migrations, and .env files. import.meta.url is a file: URL, so it also needs decoding when the path contains spaces (fileURLToPath handles that; new URL(...).pathname does not on Windows). For a path relative to the module, new URL('./file.txt', import.meta.url) avoids the conversion entirely and works with fs functions that accept URLs.

2. Extensionless and directory imports fail

js
import { helper } from './lib/helper'; // ERR_MODULE_NOT_FOUND import { helper } from './lib/helper.js'; // correct import { helper } from './lib'; // ERR_UNSUPPORTED_DIR_IMPORT import { helper } from './lib/index.js'; // correct

ESM follows the browser rule: a specifier is a URL, so the extension and the file name must be explicit. Code migrated from CommonJS compiles fine and then fails at runtime on every directory import and extensionless specifier. TypeScript users hit the same wall with "moduleResolution": "node"; "bundler" or "nodenext" is what makes the compiler agree with the runtime.

3. Named imports from a CommonJS package

js
import express from 'express'; // default = module.exports import { Router } from 'express'; // works: detected statically import legacy from 'legacy-utils'; // safe form const { parse } = legacy; // destructure at runtime

Node's ESM loader scans CommonJS source for exports.name = assignments (cjs-module-lexer) and synthesises named exports. Patterns it cannot see — module.exports = buildModuleApi(), Object.assign(exports, api), a dynamic defineProperty — leave only default available, and import { parse } from 'legacy-utils' fails with SyntaxError: Named export 'parse' not found. The portable form is a default import plus destructuring, which works regardless of how the module was written.

4. require() of an ES module

js
// Node 22.12+ / 20.19+: works if the ESM graph has no top-level await const mod = require('./esm-only.mjs'); // mod.default, and named exports // Older runtimes, or a module with top-level await: // Error [ERR_REQUIRE_ESM]: require() of ES Module ... not supported // Error [ERR_REQUIRE_ASYNC_MODULE]: ... top-level await const mod = await import('./esm-only.mjs'); // dynamic import always works

Newer LTS releases allow require() of a synchronous ESM graph, which removes most of the remaining friction for CommonJS consumers. A module that uses top-level await still cannot be loaded that way, because require is synchronous and cannot wait. Where the runtime is unknown, await import() is the portable answer; it works in both module systems and is the documented bridge.

5. exports encapsulation breaks deep imports

js
import { parse } from 'my-lib/dist/parser.js'; // ERR_PACKAGE_PATH_NOT_EXPORTED

Once exports exists, it defines the complete public surface. my-lib/dist/... is no longer reachable even though the file exists, and that is intentional — but it breaks consumers who deep-imported internals, so publishing exports is a major version change. Include "./package.json": "./package.json" because tools read it through the package name, and add explicit blocks ("./internal/*": null) rather than relying on omission when you want the intent recorded. Wildcard subpaths ("./*": "./dist/*.js") re-expose everything at the cost of the encapsulation.

6. The dual package hazard

js
// Both copies exist at runtime: ESM consumer loads index.js, CJS consumer loads index.cjs import { registry } from 'my-lib'; const legacy = require('my-lib'); registry === legacy.registry; // false: two module instances, two states

A package that ships separate ESM and CJS builds has two copies of its module-level state — caches, class identities, registries — and instanceof checks fail across the boundary. The fixes are structural: ship ESM only (with require(esm) support on modern Node), ship CJS only behind an ESM wrapper that re-exports (no separate state), or make all state live in an explicitly shared place. A Symbol.for('…') key or a global registry keeps identity across both copies when a dual build is unavoidable.

Common Node.js Runtime Mistakes

SymptomCauseFix
ReferenceError: require is not definedESM file, or "type": "module"import, or createRequire(import.meta.url)
__dirname is not definedESMimport.meta.dirname or fileURLToPath
ERR_MODULE_NOT_FOUND on a relative pathMissing extensionAdd .js / .mjs
ERR_UNSUPPORTED_DIR_IMPORTDirectory specifierImport ./dir/index.js
Named export 'x' not foundCJS module whose exports are dynamicDefault import, then destructure
ERR_REQUIRE_ESMrequire() of ESM on an older runtimeawait import(), or upgrade to 22.12+/20.19+
ERR_PACKAGE_PATH_NOT_EXPORTEDDeep import into a package with exportsUse a declared subpath, or ask for a new one
JSON import failsMissing import attributewith { type: 'json' }
Jest/Vitest cannot parse importTest runner in CJS modeConfigure ESM transform, or use vitest
Two copies of a class, instanceof falseDual package hazardOne module format, or shared global state

Try matching browser tools

All tools

Small utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Node.js guides

More in Node.js

All Node.js guides

The guides filed next to this one in Node.js, in library order.