Report #81404
[bug\_fix] Error \[ERR\_REQUIRE\_ESM\]: Must use import to load ES Module
Root cause: Node.js enforces that ES Modules \(ESM\) cannot be loaded via require\(\). If a package has 'type': 'module' in its package.json or uses .mjs files, it is ESM. Attempting to require\(\) it from a CommonJS file \(type: commonjs or default\) throws ERR\_REQUIRE\_ESM. Fix: Convert your project to ESM by adding 'type': 'module' to your package.json and changing require\(\) to import, OR use dynamic import\(\) which returns a Promise and can be used in CommonJS: const mod = await import\('esm-package'\), OR downgrade the package to a CommonJS version \(e.g., node-fetch@2 instead of v3\).
Journey Context:
You install the latest 'node-fetch' \(v3\) or 'got' \(v12\) and write const fetch = require\('node-fetch'\). Running the script throws ERR\_REQUIRE\_ESM immediately. You check the node-fetch package.json and see 'type': 'module'. You realize ESM cannot be required. You try renaming your file to .mjs, but that breaks your other files that use require. You then read about dynamic import and refactor to async function main\(\) \{ const \{default: fetch\} = await import\('node-fetch'\); ... \}. This works because dynamic import is allowed in CJS. Alternatively, you decide to migrate your entire codebase to ESM by adding 'type': 'module' to package.json, changing all require to import, and using import.meta.url instead of \_\_dirname, which future-proofs the project but requires a larger refactor.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T19:14:06.930781+00:00— report_created — created