Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

ERR_REQUIRE_ESM and __dirname Is Not Defined in ESM Projects

require of an ESM-only package has nothing to load, and ESM creates none of the CommonJS wrapper globals. Dynamic import, createRequire, and the path replacements.

~4 min readNode.js
#Node.js#ESM#CommonJS#Modules
3D illustration of two module cubes facing each other with a hollow ring socket and a square plug that do not fit

Introduction & Quick Summary

Symptom. Two errors that usually arrive together. Adding a package to a CommonJS service breaks startup: Error [ERR_REQUIRE_ESM]: require() of ES Module /app/node_modules/node-fetch/src/index.js from /app/index.js not supported. Or, after adding "type": "module" to package.json, the first file that uses a path fails with ReferenceError: __dirname is not defined in ES module scope — and often require is not defined beside it.

Cause. ERR_REQUIRE_ESM means your CommonJS file is require()ing a package that publishes only an ESM entry, and the condition require has nothing to load. The second is the opposite direction of the same change: ES modules have no __dirname, __filename, require or module, because those are CommonJS wrapper variables that ESM scope never creates — import.meta.url replaces them.

Fix. For the import: await import() from CommonJS, or convert the file to ESM; on Node 22.12+ require() of an ESM module without top-level await works natively, so upgrading is the smallest change. For the paths: use import.meta.dirname (Node 20.11+), or fileURLToPath(new URL('.', import.meta.url)) where you must support older runtimes, and createRequire(import.meta.url) when you still need require.

Core Mechanics, Signatures & Reproducible Setup

The failing shape and the fixed one side by side:

js
// index.js — CommonJS because package.json has no "type" const fetch = require('node-fetch'); // ERR_REQUIRE_ESM: node-fetch 3 is ESM-only const path = require('node:path'); const file = path.join(__dirname, 'data.json'); // fine in CJS
js
// index.mjs — ES module import { readFile } from 'node:fs/promises'; import path from 'node:path'; const here = import.meta.dirname ?? path.dirname(new URL(import.meta.url).pathname); const data = JSON.parse(await readFile(path.join(here, 'data.json'), 'utf8')); const { default: fetch } = await import('node-fetch'); // only when you must stay lazy

For a large CommonJS codebase, the least invasive fix is createRequire, which restores a require bound to the module's own resolution context:

js
import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; import path from 'node:path'; const require = createRequire(import.meta.url); const pkg = require('./package.json'); // JSON and CJS deps both work const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __filename = fileURLToPath(import.meta.url);

createRequire returns a real CommonJS require with resolve, cache, and main, so libraries that expect CJS keep working. It cannot load an ESM-only package, because that is the same limitation.

Key Comparison Table

GlobalCommonJSES module
__dirnameAvailableimport.meta.dirname (Node 20.11+), or fileURLToPath
__filenameAvailableimport.meta.filename (Node 20.11+)
require()AvailablecreateRequire(import.meta.url)
module.exportsAvailableexport / export default
import.meta.urlundefined (or via a shim)Available
Top-level awaitNoYes
Path resolutionAdds extensions, index filesExact specifier, no guessing
this at top levelmodule.exportsundefined
Package situationrequire() from CJSFix
"type": "module", exports.import onlyERR_REQUIRE_ESM on Node < 22.12await import(), or upgrade Node
ESM with top-level awaitFails even on 22.12+await import() only
Dual package (import + require)Works, but two instancesCheck for state duplication
exports without a require conditionERR_PACKAGE_PATH_NOT_EXPORTEDUse the documented entry
ESM-only dependency deep importERR_PACKAGE_PATH_NOT_EXPORTEDNot exposed; use the public entry

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. __dirname in a CLI that walks up to the project root

import.meta.dirname is the directory of the current module; walking up works exactly as before, and process.cwd() is the wrong substitute because it depends on where the user ran the command:

js
import path from 'node:path'; const root = path.resolve(import.meta.dirname, '..'); // package root, not cwd

If the file is bundled, import.meta.url can point inside the bundle; bundlers offer their own replacement (__dirname is still injected by webpack in output formats that support it).

2. require of a JSON file in ESM

import data from './data.json' with { type: 'json' } is the standard syntax and is supported in Node 22 with the attribute; without it Node throws ERR_IMPORT_ATTRIBUTE_MISSING. The createRequire route avoids the attribute entirely and is the pragmatic choice for config files:

js
const require = createRequire(import.meta.url); const config = require('../config/app.json');

3. ERR_REQUIRE_ESM inside a dependency you cannot change

A CJS library requires an ESM-only package internally and throws from its own code. You cannot patch node_modules durably; pick one of three real options: upgrade the library to a version that supports ESM, move your code to ESM so the chain stays ESM, or pin the ESM-only package to an older CJS major in overrides/resolutions while you migrate.

jsonc
{ "overrides": { "node-fetch": "^2.7.0" } // temporary, forces the CJS release }

4. TypeScript emitting the wrong module format

"module": "esnext" with "type": "commonjs" produces import statements in .js files that Node parses as CJS: SyntaxError: Cannot use import statement outside a module. The tsconfig and the type field must agree, or the output extension must decide it (.mjs/.cjs).

jsonc
{ "compilerOptions": { "module": "nodenext", // follows package.json "type" "moduleResolution": "nodenext", "verbatimModuleSyntax": true } }

5. Tests that lose __dirname after the migration

Jest runs CJS by default and fails on ESM with Cannot use import statement outside a module; enabling --experimental-vm-modules and extensionsToTreatAsEsm works but needs import.meta handling. Vitest and node:test are simpler for new ESM code, and node --test needs no configuration at all:

bash
node --test --experimental-test-coverage

6. ESM entry points that resolve differently

import.meta.resolve('pkg') returns a URL string, not a path, and does not check that the file exists in all versions. Convert before fs calls, and never concatenate a raw file: URL:

js
import { fileURLToPath } from 'node:url'; const entry = fileURLToPath(import.meta.resolve('some-pkg'));

Common Compilation/Runtime Mistakes & Version Gotchas

  • "type": "module" added globally. Every .js in the package becomes ESM at once, including test helpers and config files that use module.exports. Convert incrementally with .mjs, or set type per package.
  • Assuming Node 22 require(esm) covers everything. A module with top-level await still throws ERR_REQUIRE_ASYNC_MODULE; the error names the module, and await import() is the only route.
  • __dirname shims copied from old blog posts. path.dirname(fileURLToPath(import.meta.url)) works; new URL('.', import.meta.url).pathname breaks on Windows (/C:/…) and on paths with spaces (%20).
  • module.exports left in place after conversion. It becomes a ReferenceError in ESM; a mixed file that needs both is a sign to split it.
  • Bundled dependencies in serverless output. A bundler may inline an ESM-only package into CJS, which works until it uses top-level await. Check the platform's module format instead of guessing.
  • exports maps hide files you used to import. After a dependency adds exports, pkg/dist/x.js deep imports throw ERR_PACKAGE_PATH_NOT_EXPORTED. Use the documented entry point.
  • Dynamic import() in CJS returns a namespace object. Named exports are on the object, and the default export is under .default; a direct require-style usage silently gets the wrong shape (a common cause of fetch is not a function).

Related tools. Encode or decode the file: URLs that appear in ESM stack traces with the URL encoder, format the package.json exports block before comparing two versions with the JSON formatter, and diff a converted file against its CommonJS original with the text diff so a dropped export shows up immediately.

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.