Skip to content
Latchkey

Node "ReferenceError: require is not defined in ES module scope" in CI

The file is being executed as an ES module (because of "type": "module" or a .mjs extension), and require is a CommonJS-only global that does not exist in ESM scope.

What this error means

After switching a package to "type": "module", a leftover require(...) call fails with "ReferenceError: require is not defined in ES module scope, you can use import instead".

node
const path = require('node:path');
            ^

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

Common causes

CommonJS require() left in an ESM file

After adding "type": "module", files still call require(...), which is undefined in module scope.

A dependency or snippet copied from CJS docs

Sample code written for CommonJS uses require(); pasted into an ESM project it throws on first call.

How to fix it

Replace require with import

Use static import for ESM, which is the supported way to load modules in module scope.

index.js
import path from 'node:path';
import { readFile } from 'node:fs/promises';

Recreate require with createRequire if needed

When you must call CommonJS-style require (for a CJS-only addon), build one from module.

index.js
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const native = require('./build/Release/addon.node');

How to prevent it

  • Convert all require() calls when adding "type": "module".
  • Use import consistently in ESM files.
  • Reserve createRequire for genuine CommonJS-only interop.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →