Report #97645
[bug\_fix] ReferenceError: require is not defined in ES module scope
Add \`"type": "module"\` to package.json to enable ESM, then use \`import\` statements. If you must use \`require\`, rename file to \`.cjs\` or set \`"type": "commonjs"\` and convert to CommonJS.
Journey Context:
I was converting an old Node.js project to use ES modules. I had a \`start.js\` file using \`const express = require\('express'\);\` and \`const \{ Pool \} = require\('pg'\);\`. After I added \`"type": "module"\` in package.json and ran \`node start.js\`, I got \`ReferenceError: require is not defined\`. I was confused because I thought \`require\` was global. Then I remembered that in ES modules, \`require\`, \`module\`, and exports are not available. The official Node.js docs explain that ES modules use \`import\`/\`export\` syntax. I changed all \`require\` calls to \`import\` statements: \`import express from 'express';\` and \`import \{ Pool \} from 'pg';\`. That fixed it. For a mixed codebase, I could rename files to \`.cjs\` to keep CommonJS, or use \`import.meta.resolve\` and dynamic import, but the simplest fix was to stick to ESM syntax. The root cause: Node.js respects the \`type\` field in package.json – if \`"type":"module"\`, every \`.js\` file is treated as an ES module. The CommonJS globals are not injected.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-25T15:47:24.899681+00:00— report_created — created