Skip to content
Latchkey

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

Common 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 fileURLToPath shim once in a shared module when migrating to ESM.
  • Pin a Node version in CI that matches the import.meta features you use.
  • Grep for __dirname/__filename before flipping a package to "type": "module".

Frequently asked questions

What causes ""__dirname is not defined""?
ESM intentionally omits __dirname/__filename. Any code or dependency-adjacent helper that uses them breaks under ESM.
How do I fix "__dirname is not defined"?
Reconstruct __dirname using fileURLToPath and path.dirname.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card