Report #9107
[bug\_fix] ReferenceError: require is not defined in ES module scope / Error \[ERR\_REQUIRE\_ESM\]
Rename the file to use the .cjs extension to force CommonJS, or convert all require\(\) calls to ESM import statements and ensure the file is treated as a module \(via .mjs or package.json "type": "module"\). Root cause: When Node.js treats a file as an ES Module \(via "type": "module" or .mjs\), the require\(\) function does not exist in that scope; only import is available.
Journey Context:
A developer decides to migrate their Node.js project to ES Modules by adding "type": "module" to the root package.json. Immediately upon running node src/index.js, the process crashes with 'ReferenceError: require is not defined in ES module scope'. The stack trace points to a legacy config file that still uses const fs = require\('fs'\). The developer realizes they need a hybrid approach: they rename the legacy config file to config.cjs to explicitly mark it as CommonJS, allowing the rest of the application to use ESM. Alternatively, they could refactor the file to use import fs from 'fs'.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T07:17:40.349396+00:00— report_created — created