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.

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
{
"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
}
}// 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');// 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 insideKey Comparison Table
| Feature | CommonJS | ES modules |
|---|---|---|
| Statement | require(), module.exports | import, export |
| Resolution time | At call | Before evaluation, statically |
__dirname / __filename | Available | import.meta.dirname / .filename |
| Extension in specifier | Optional, guessed | Required |
Directory index.js | Resolved automatically | Not resolved |
NODE_PATH | Honoured | Ignored |
Top-level await | Not allowed | Allowed |
this at top level | module.exports | undefined |
| Bindings | Copied values | Live, read-only |
| Strict mode | Opt-in | Always |
| JSON import | require('./x.json') | with { type: 'json' } |
Condition key in exports | Chosen when | Order rule |
|---|---|---|
types | TypeScript resolution | First, or types are missed |
node | Any Node.js runtime | Before default |
import | import statement or import() | Before require |
require | require() call | After import |
browser | Bundlers targeting browsers | Tool-specific |
default | Nothing else matched | Always last |
Practical Edge Cases and Deep Dives
1. __dirname is not defined
// 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
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'; // correctESM 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
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 runtimeNode'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
// 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 worksNewer 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
import { parse } from 'my-lib/dist/parser.js'; // ERR_PACKAGE_PATH_NOT_EXPORTEDOnce 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
// 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 statesA 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
| Symptom | Cause | Fix |
|---|---|---|
ReferenceError: require is not defined | ESM file, or "type": "module" | import, or createRequire(import.meta.url) |
__dirname is not defined | ESM | import.meta.dirname or fileURLToPath |
ERR_MODULE_NOT_FOUND on a relative path | Missing extension | Add .js / .mjs |
ERR_UNSUPPORTED_DIR_IMPORT | Directory specifier | Import ./dir/index.js |
Named export 'x' not found | CJS module whose exports are dynamic | Default import, then destructure |
ERR_REQUIRE_ESM | require() of ESM on an older runtime | await import(), or upgrade to 22.12+/20.19+ |
ERR_PACKAGE_PATH_NOT_EXPORTED | Deep import into a package with exports | Use a declared subpath, or ask for a new one |
| JSON import fails | Missing import attribute | with { type: 'json' } |
Jest/Vitest cannot parse import | Test runner in CJS mode | Configure ESM transform, or use vitest |
Two copies of a class, instanceof false | Dual package hazard | One module format, or shared global state |
Try matching browser tools
All toolsSmall utilities that fit Node.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Node.js guides
All Node.js guidesNode.js EventEmitter: once, error Events, and Listener Memory Leaks
emit is synchronous, so a throwing listener aborts the rest. An error event with no listener crashes the process, and a listener per request is the classic leak.
Node.js fs/promises: Read, Write, Watch, and Atomic File Operations
writeFile truncates before writing, so a crash leaves half a file. The atomic pattern is temp file, fsync, rename; readFile loads everything, so large files need streams.
Node.js Streams: Readable, Writable, Transform, and pipeline
pipe() forwards data but not errors; pipeline() destroys the chain and rejects. Backpressure is the false return from write(), and _flush that never calls back hangs forever.
Node.js crypto: Hashing, HMAC, AES-GCM, and Random Bytes
Hashing, HMAC, AES-256-GCM and randomness solve different problems. Never reuse a GCM nonce, never hash a password with sha256, and compare secrets with timingSafeEqual.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.