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
92%Fix Rate
95%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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.
genericWorkarounds
-
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
-
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:
-
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
-
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: