Report #93583
[bug\_fix] Error \[ERR\_REQUIRE\_ESM\]: require\(\) of ES Module
Convert the importing file to ESM by using \`.mjs\` extension or adding \`"type": "module"\` to package.json, then use ES \`import\` syntax. Alternatively, use dynamic \`import\(\)\` which returns a Promise and works in CommonJS. Root cause: ES modules use a different loading mechanism \(static, async\) than CommonJS \(synchronous, dynamic\), and Node enforces that ESM cannot be loaded via require\(\).
Journey Context:
You upgrade \`chalk\` to v5 in your Express server. On startup, Node throws ERR\_REQUIRE\_ESM pointing at \`const chalk = require\('chalk'\)\`. Checking chalk's package.json, you see \`"type": "module"\`. You try using \`createRequire\` but it doesn't bypass the ESM restriction. You learn that ES modules are statically parsed, allowing top-level await and tree-shaking, but cannot be synchronously required. The fix requires converting your entry point to ESM by renaming to \`.mjs\` or setting \`"type": "module"\` in package.json, then replacing all \`require\(\)\` with \`import\` statements and \`module.exports\` with \`export\`. For CommonJS compatibility, you use dynamic \`import\('chalk'\)\` which returns a Promise, allowing ESM loading in .js files. This works because Node's ES module loader handles the asynchronous resolution and linking of ES modules separately from the CommonJS loader.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T15:39:59.640479+00:00— report_created — created