ReferenceError: require is not defined in ES module scope
A file is an ES module because of its extension or package type, and require does not exist there. Convert, rename to .cjs, or use createRequire.

Introduction & Quick Summary
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and
'/app/package.json' contains "type": "module". To treat it as a CommonJS script,
rename it to use the '.cjs' file extension.Node.js decided the file is an ES module and then encountered require, module, exports, __dirname or __filename, none of which exist in ESM. The message is precise about the reason: the file extension plus the nearest package.json "type" field. Setting "type": "module" is the most common trigger, and the second most common is a .mjs extension or a transpiler that emitted ESM while the code still used CommonJS globals.
| Signal in the error | Meaning | Fastest fix |
|---|---|---|
contains "type": "module" | Nearest package.json opts into ESM | Rename to .cjs or convert imports |
has a '.mjs' file extension | Extension forces ESM | Rename to .cjs for CommonJS code |
in ES module scope with no detail | Transpiler emitted ESM | Check tsconfig module or bundler target |
__dirname is not defined | Same root cause, different global | Use import.meta.dirname (Node 21.2+) |
module is not defined | Same root cause | Remove the CommonJS guard |
Core Mechanics, Signatures & Reproducible Setup
Node resolves module format per file, not per project. The chain is: .mjs is always ESM, .cjs is always CommonJS, and .js follows the nearest package.json "type" ("module" means ESM, anything else or absent means CommonJS). Once a file is ESM, the CommonJS wrapper parameters (exports, require, module, __filename, __dirname) are not injected, and referencing them throws this error.
Reproduce it exactly:
mkdir -p /tmp/esm-require && cd /tmp/esm-require
printf '{"name":"demo","type":"module"}\n' > package.json
printf 'const fs = require("fs");\nconsole.log(fs.existsSync("."));\n' > index.js
node index.js
# ReferenceError: require is not defined in ES module scope, you can use import insteadThree correct conversions, each with a different cost:
// 1. Native ESM
import fs from "node:fs";
import { readFile } from "node:fs/promises";
console.log(fs.existsSync("."));// 2. Keep CommonJS by renaming the file
// mv index.js index.cjs (no package.json change needed)
const fs = require("node:fs");// 3. Bridge inside ESM when a dependency has no ESM entry
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const legacy = require("legacy-package");createRequire is the supported escape hatch for the last mile of a migration, but it defeats tree shaking and is worth removing once the dependency ships an ESM build.
Replacements for the four globals that vanish:
import { fileURLToPath } from "node:url";
import path from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Node 21.2+ and 20.11+
console.log(import.meta.dirname, import.meta.filename);Key Comparison Table
| File / package state | Format | require | import | __dirname |
|---|---|---|---|---|
.js, no type | CommonJS | Works | Syntax error | Works |
.js, "type": "module" | ESM | This error | Works | Undefined |
.cjs | CommonJS | Works | Syntax error | Works |
.mjs | ESM | This error | Works | Undefined |
.mts compiled to .mjs | ESM | This error | Works | Undefined |
Dual package with exports map | Depends on consumer | Depends | Depends | Depends |
| Approach | Interop with CommonJS deps | Static analysis | Migration effort |
|---|---|---|---|
Convert to import | Yes, default export interop | Full | Medium |
Rename to .cjs | Yes | None in ESM tools | Trivial |
createRequire | Yes | Broken | Low |
Dynamic await import() | Yes | Partial | Low |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: A TypeScript project that emits ESM
TypeScript does not own runtime format; the output does. If tsconfig.json says "module": "nodenext" and package.json has "type": "module", every .ts file becomes .mjs-like and any require in the source survives the transpile.
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"target": "es2023"
}
}Convert the source to import, or set "module": "commonjs" and remove "type": "module" from the package. Mixing them is where most of these errors come from.
Case 2: A single config file loads as ESM
tailwind.config.js, postcss.config.js and eslint.config.js are read by the package's own module type. Dropping "type": "module" into a Next.js package suddenly makes module.exports = {...} throw.
// tailwind.config.js in an ESM package
export default { content: ["./src/**/*.{ts,tsx}"] };Alternatively rename to tailwind.config.cjs and keep the CommonJS object.
Case 3: Jest and the --experimental-vm-modules split
Jest transforms files through Babel, so a require in a test can survive into a context that treats the module as ESM.
// jest.config.cjs
module.exports = { transform: { "^.+\\.tsx?$": "ts-jest" } };Keep Jest config in .cjs, and if you enable extensionsToTreatAsEsm, convert test files as well.
Case 4: A dependency's entry point chose the format
require() of ES Module /node_modules/p-map/index.js from /app/dist/loader.js not supported.The mirror error appears when CommonJS code requires an ESM-only package. The fix is the same migration in reverse: const { default: pMap } = await import("p-map"), or upgrade the parent to ESM.
Case 5: Bundled output that mixes formats
A library built twice (ESM and CJS) can ship a CJS bundle that contains require after a bundler rewrote it as ESM. Check the published files:
node -e "const p=require('./package.json'); console.log(p.type, p.exports)"Publish dist/index.mjs and dist/index.cjs and point exports at each, rather than relying on one file to satisfy both.
Case 6: __dirname inside a dynamically loaded worker
Workers and child processes do not inherit module globals either. Pass the resolved path from the parent process instead of recomputing it:
new Worker(new URL("./worker.js", import.meta.url));new URL with import.meta.url is the ESM-safe equivalent of path.join(__dirname, ...) and works for worker_threads, child_process.fork and dynamic import().
Common Compilation/Runtime Mistakes & Version Gotchas
- Node 22 and later can
require()ESM.--experimental-require-modulebecame the default in Node 22.12 and stable later, so arequireof a synchronous ESM module may work there and still fail in Node 20 CI. Test on the lowest version you support. - Top-level
awaitneeds ESM. A file using top-levelawaitcannot be CommonJS, which is a common reason people flip"type": "module"and then hit this error in the same commit. "type": "module"applies to the whole subtree. Every.jsfile below thatpackage.json, including scripts you never converted, changes format at once. Addpackage.jsonboundaries per folder when only part of a monorepo should migrate.require.resolvehas no direct ESM equivalent. Useimport.meta.resolve(specifier)where available, which is synchronous in current Node.- Bundlers ignore the runtime rule. esbuild and webpack rewrite
requireregardless of"type", so code that works under the bundler can fail under plainnode. Validate withnode --checkon the emitted file. - Shebang scripts. A
#!/usr/bin/env nodefile named.jsin an ESM package must useimportsyntax even though it starts with a shebang.
If the project's package.json and tsconfig.json disagree, paste both into the JSON formatter to compare type, module and exports fields side by side, and use the diff tool when a working branch and a broken one differ in configuration. Environment-specific flags such as NODE_OPTIONS=--experimental-require-module belong in the env file viewer so the difference between local and CI is visible.
Primary references: the Node.js ESM documentation defines format detection and import.meta, and module.createRequire documents the bridging API.
Official references
primary documentationThe Node.js documentation that defines the behaviour this guide explains.
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 ERR_INVALID_ARG_TYPE: the argument must be of type
ERR_INVALID_ARG_TYPE is Node's validator naming a wrong argument. Read the quoted argument, validate at the boundary and default env values.
ERR_MODULE_NOT_FOUND: Cannot find module imported from an ESM file
ESM resolves specifiers literally: extensions are required, directories do not resolve to index files, and exports maps block deep imports.
Node.js: UnhandledPromiseRejectionWarning and ERR_UNHANDLED_REJECTION
Since Node 15 an unhandled rejection crashes the process. Await or return every promise, catch async callbacks and shut down cleanly when one escapes.
Node.js ERR_STREAM_WRITE_AFTER_END: write after end
Write after end means something ended the stream first. Find the double end, guard with writableEnded and let pipeline own the lifecycle.
More in Node.js
All Node.js guidesThe guides filed next to this one in Node.js, in library order.