node modules ai_generated true

ReferenceError: require is not defined in ES module scope, you can use import instead

ID: node/node-esm-require-error

Also available as: JSON · Markdown
92%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
20 active

Root Cause

Code uses require() inside an ES module. When package.json has "type": "module" or the file has .mjs extension, require() is not available.

generic

Workarounds

  1. 95% success Replace require() calls with import statements or dynamic import()
    Change const x = require('x') to import x from 'x' (static) or const x = await import('x') (dynamic)

    Sources: https://nodejs.org/api/esm.html

  2. 88% success Use createRequire to get a require function in ESM
    import { createRequire } from 'module'; const require = createRequire(import.meta.url); const pkg = require('./package.json');

    Sources: https://nodejs.org/api/module.html#modulecreaterequirefilename

Dead Ends

Common approaches that don't work:

  1. Adding a polyfill for require in ESM context 70% fail

    Fragile workaround that breaks module resolution semantics and can cause subtle bugs with __dirname and __filename

  2. Renaming files from .mjs to .js without changing package.json type field 75% fail

    If package.json has "type": "module", all .js files are still treated as ESM

Error Chain

Leads to:
Preceded by:
Frequently confused with: