In Node.js, why does `import './utils'` fail in an ES module when `require('./utils')` finds `utils.js` from CommonJS?
answer
- URL resolution, not path guessing
- no extension search, no folder index
- ERR_MODULE_NOT_FOUND with a hint
- ERR_UNSUPPORTED_DIR_IMPORT for folders
basics
~10 sNode's ES module resolver resolves relative specifiers as URLs and never adds extensions or looks for index files, so './utils' must be written './utils.js'. A missing file throws ERR_MODULE_NOT_FOUND; a folder throws ERR_UNSUPPORTED_DIR_IMPORT.
solid answer
~40 s`require()` guesses: it tries `./utils`, then `./utils.js`, `./utils.json` and `./utils.node`, then a folder with `index.js`. Node's ES module resolver does none of that. It treats a relative specifier as a URL relative to the importing module's `import.meta.url`, checks that exact file, and fails with `ERR_MODULE_NOT_FOUND` ("Cannot find module ... imported from ..."). Node adds a hint such as `Did you mean to import "./utils.js"?` when the CommonJS rules would have found something. Importing a folder like `'./routes'` throws `ERR_UNSUPPORTED_DIR_IMPORT`. The same applies to a deep import into a package that has no `"exports"` map: `some-package/lib/x` needs `x.js`. The fix is to write full specifiers, or give the folder a name through `"exports"` or `"imports"`.
code
javascript · 8 lines// /srv/api/src/server.js in a package with "type": "module"
import { slugify } from './utils.js'; // OK: exact file
import routes from './routes/index.js'; // OK: index named explicitly
// import { slugify } from './utils'; // ERR_MODULE_NOT_FOUND
// import routes from './routes'; // ERR_UNSUPPORTED_DIR_IMPORT
console.log(import.meta.resolve('./utils.js'));
// file:///srv/api/src/utils.jsgo deeper
Remember that relative imports in Node's ES modules need the full filename, extension included, and that importing a folder is an error.
Explain the URL-based resolver: no extension search, no folder index, NODE_PATH ignored, and how bare names with and without an exports map differ.
Plan the CommonJS-to-import path work: find folder and extensionless imports, read the ERR_MODULE_NOT_FOUND hints, and replace folder indexes with imports or exports entries.
Weigh rewriting specifiers across a large codebase against keeping CommonJS rules through createRequire or hooks, and set the convention new code must follow.
## Two resolvers with different rules Node.js ships two module loaders. The **CommonJS loader** serves `require()`; the **ES module loader** serves `import` declarations and `import()` expressions. They share the package machinery (`node_modules`, `"exports"`, `"imports"`), but they resolve **file paths** very differently. | Behaviour | `require()` (CommonJS) | `import` (ES modules) | |---|---|---| | Missing extension | Tries `.js`, `.json`, `.node` | No extension search | | Folder as specifier | Uses `package.json` `"main"`, then `index.js` | `ERR_UNSUPPORTED_DIR_IMPORT` | | `NODE_PATH` | Searched after `node_modules` | Ignored | | `require.extensions` | Consulted | Not used | | Failure code | `MODULE_NOT_FOUND` | `ERR_MODULE_NOT_FOUND` | ## Why the ES module resolver refuses to guess ES modules in Node are **resolved and cached as URLs**. A relative specifier such as `./utils` is resolved against the importing module's URL with standard URL rules, which yields `file:///srv/api/src/utils`. Node then checks whether that exact file exists. Nothing in that algorithm appends `.js` or looks inside a directory, because: - Node's documentation ties it to the browser: it matches how `import` behaves there, assuming a typically configured server; - a specifier resolves to one URL without trial and error, so what loads is predictable from the text alone; - every guess the CommonJS loader makes is an extra filesystem check, and a large dependency graph makes many of them at start-up. ## What the failures look like A missing extension produces an error with code `ERR_MODULE_NOT_FOUND` whose message names the resolved path and the importer, and Node appends a hint when the CommonJS rules would have found a file: ```plaintext Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/srv/api/src/utils' imported from /srv/api/src/server.js Did you mean to import "./utils.js"? ``` A specifier that resolves to a directory fails differently, with `ERR_UNSUPPORTED_DIR_IMPORT` ("Directory import ... is not supported resolving ES modules imported from ..."). Code that relied on `require('./routes')` loading `routes/index.js` hits this the day it moves to `import`. ## Bare specifiers follow the same rule, mostly For a package name the ES module resolver still walks `node_modules` folders. What happens next depends on the package: 1. **The package has `"exports"`**: the subpath must match an exports key, and the extension is whatever the key says. `import 'some-package/feature'` works if `"./feature"` is a key, even though no file has that name. 2. **No `"exports"`, bare name only**: Node falls back to `"main"` and the legacy index lookup, so `import 'some-package'` usually still works. 3. **No `"exports"`, deep subpath**: the subpath is a plain URL inside the package folder, so `import 'some-package/lib/x'` fails where `'some-package/lib/x.js'` works. ## Fixing a codebase that hits this - **Write full relative specifiers**: `./utils.js`, `./routes/index.js`. This is the change Node expects, and editors can automate it. - **Name internal entry points** with the `"imports"` field (`"#routes": "./src/routes/index.js"`) or, inside a published package, with `"exports"`, so callers stop depending on folder layout. - **Use `import.meta.resolve()`** to see what a specifier resolves to without loading it, the ES module counterpart of `require.resolve()`. - **Keep `require()` where you need its rules**: `module.createRequire()` gives an ES module a CommonJS `require`, and module customization hooks can change resolution; both belong to the loader material elsewhere in this course. ## Finding the problem before production does Resolution errors surface when a module is first loaded, so a lazily loaded `import()` path can pass every start-up check and fail on the first request that reaches it. Two habits catch them earlier: 1. **Load every entry point in a test.** A smoke test that imports each route module, job and script resolves their static import graphs, so a missing extension fails in CI rather than on a live request. 2. **Resolve the dynamic ones explicitly.** For `import()` calls built from known strings, `import.meta.resolve()` in a test checks each specifier without running the module. Errors from inside dependencies are worth reading closely: the `imported from` part of the message names the file with the bad specifier, which is often a package's own build output rather than your code. Note that `.json` targets also need an import attribute (`with { type: 'json' }`) under `import`, which is a loading rule rather than a resolution rule.
- Why does `import 'some-package'` often work in Node.js when `import 'some-package/lib/x'` fails?For a package without `"exports"`, the bare name falls back to `"main"` and the legacy index lookup, which still tries extensions. A deep subpath gets none of that: it is resolved as a plain URL inside the package folder, so it needs the real filename with its extension. If the package has `"exports"`, only its listed subpaths work at all.
- How can you check in Node.js what an ES module specifier resolves to without loading it?Call `import.meta.resolve(specifier)` inside the module. It returns the absolute URL string synchronously and honours the full resolution algorithm, including `"exports"` restrictions. It may perform synchronous filesystem work, so use it for diagnostics or one-off lookups rather than in a hot path.
- Node's ES module loader tries .js automatically like require does
- import './routes' loads routes/index.js just as require does
- NODE_PATH works for import specifiers in ES modules
- Every bare package import must also spell out the file extension
- The ERR_MODULE_NOT_FOUND hint means Node loaded the suggested file anyway