Node.js "__dirname is not defined in ES module scope" in CI
ESM does not define __dirname or __filename. Code that relied on those CommonJS globals throws a ReferenceError once the file runs as an ES module.
What this error means
After enabling "type": "module" (or running a built ESM bundle), any use of __dirname/__filename fails in CI with a ReferenceError.
node
ReferenceError: __dirname is not defined in ES module scope
at file:///work/repo/dist/config.js:4:21Common causes
CommonJS globals removed in ESM
ESM intentionally omits __dirname/__filename. Any code or dependency-adjacent helper that uses them breaks under ESM.
How to fix it
Derive the directory from import.meta.url
Reconstruct __dirname using fileURLToPath and path.dirname.
src/config.js
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);Use import.meta.dirname on newer Node
Recent Node versions expose import.meta.dirname and import.meta.filename directly.
src/config.js
const here = import.meta.dirname; // Node 20.11+ / 21.2+How to prevent it
- Add the
fileURLToPathshim once in a shared module when migrating to ESM. - Pin a Node version in CI that matches the
import.metafeatures you use. - Grep for
__dirname/__filenamebefore flipping a package to"type": "module".
Related guides
Node.js "Must use import to load ES Module" (CJS requiring ESM) in CIFix ERR_REQUIRE_ESM "Must use import to load ES Module" in CI - a CommonJS file called require() on a depende…
Node "Must use import to load ES Module" - Fix require() of ESM in CIFix Node "Error [ERR_REQUIRE_ESM]: Must use import to load ES Module" in CI - CommonJS code require()-ing a p…
Node.js "ERR_UNSUPPORTED_DIR_IMPORT" During Build in CIFix Node.js ERR_UNSUPPORTED_DIR_IMPORT in CI - an ESM import targeted a directory instead of a file, which th…