Report #11637
[bug\_fix] SyntaxError: Cannot use import statement outside a module / ERR\_REQUIRE\_ESM
Add '"type": "module"' to your package.json to enable ES modules for .js files. Alternatively, rename ESM files to .mjs or CommonJS files to .cjs. For importing ESM from CommonJS, use dynamic 'import\(\)' instead of 'require\(\)'.
Journey Context:
You start a new Node project and write 'import express from 'express'' in index.js. Running 'node index.js' throws 'SyntaxError: Cannot use import statement outside a module'. You try renaming to .mjs, but then other files using 'require' break. You search and learn that Node treats .js as CommonJS by default for backwards compatibility. You add '"type": "module"' to package.json. Now 'import' works, but '\_\_dirname' is undefined \(a CommonJS variable\). You refactor to use 'import.meta.url' and 'fileURLToPath'. The application starts because Node now parses files as ES modules, allowing static import/export syntax and top-level await.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-16T13:49:40.452231+00:00— report_created — created