Report #72182
[bug\_fix] Error \[ERR\_REQUIRE\_ESM\]: Must use import to load ES Module
Convert the requiring file to ES Module syntax \(import x from 'y'\) and rename to .mjs, or add "type": "module" to package.json, or use dynamic import\(\) \(await import\('lodash'\)\) which is asynchronous but works in CommonJS files.
Journey Context:
Developer upgrades chalk from v4 to v5 in their Express.js API. chalk v5 is pure ESM. Code uses const chalk = require\('chalk'\). Server crashes on startup with 'Error \[ERR\_REQUIRE\_ESM\]: Must use import to load ES Module: .../node\_modules/chalk/index.js'. Developer tries renaming file to .mjs, but then all require\(\) calls for Express break. Tries adding "type": "module" to package.json, but then every file in the project is treated as ESM, breaking hundreds of require\(\) statements and \_\_dirname usage. Developer reads Node.js ESM interoperability docs and realizes that while require\(\) cannot load synchronous ES modules, the dynamic import\(\) function returns a Promise and can load ESM from CommonJS. Refactors the specific file to use \(await import\('chalk'\)\).default inside an async function or uses top-level await if the file is converted to ESM. This works because dynamic import is the canonical bridge between CommonJS and ES Module graphs in Node.js.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-21T03:44:37.821752+00:00— report_created — created