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.
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.
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.
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".