Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readNode.js
#Node.js#ESM#Modules#Migration
A Node module crate labelled ESM beside a cyan import arrow and an amber .cjs fallback key

Introduction & Quick Summary

text
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 errorMeaningFastest fix
contains "type": "module"Nearest package.json opts into ESMRename to .cjs or convert imports
has a '.mjs' file extensionExtension forces ESMRename to .cjs for CommonJS code
in ES module scope with no detailTranspiler emitted ESMCheck tsconfig module or bundler target
__dirname is not definedSame root cause, different globalUse import.meta.dirname (Node 21.2+)
module is not definedSame root causeRemove 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:

bash
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 instead

Three correct conversions, each with a different cost:

js
// 1. Native ESM import fs from "node:fs"; import { readFile } from "node:fs/promises"; console.log(fs.existsSync("."));
js
// 2. Keep CommonJS by renaming the file // mv index.js index.cjs (no package.json change needed) const fs = require("node:fs");
js
// 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:

js
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 stateFormatrequireimport__dirname
.js, no typeCommonJSWorksSyntax errorWorks
.js, "type": "module"ESMThis errorWorksUndefined
.cjsCommonJSWorksSyntax errorWorks
.mjsESMThis errorWorksUndefined
.mts compiled to .mjsESMThis errorWorksUndefined
Dual package with exports mapDepends on consumerDependsDependsDepends
ApproachInterop with CommonJS depsStatic analysisMigration effort
Convert to importYes, default export interopFullMedium
Rename to .cjsYesNone in ESM toolsTrivial
createRequireYesBrokenLow
Dynamic await import()YesPartialLow

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.

js
// 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.

js
// 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

text
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:

bash
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:

js
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-module became the default in Node 22.12 and stable later, so a require of a synchronous ESM module may work there and still fail in Node 20 CI. Test on the lowest version you support.
  • Top-level await needs ESM. A file using top-level await cannot 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 .js file below that package.json, including scripts you never converted, changes format at once. Add package.json boundaries per folder when only part of a monorepo should migrate.
  • require.resolve has no direct ESM equivalent. Use import.meta.resolve(specifier) where available, which is synchronous in current Node.
  • Bundlers ignore the runtime rule. esbuild and webpack rewrite require regardless of "type", so code that works under the bundler can fail under plain node. Validate with node --check on the emitted file.
  • Shebang scripts. A #!/usr/bin/env node file named .js in an ESM package must use import syntax 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 documentation

The Node.js documentation that defines the behaviour this guide explains.

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.