ES Modules Logo ESModules.com

Module Resolution

Resolution is the step that turns a specifier into an absolute URL. Everything else - fetching, parsing, linking - happens after that URL exists.

This page follows a specifier from the moment you write it: the kinds of specifier, when a file extension is required, how directories resolve, and the order the lookup runs in. It also covers self-referencing imports, import maps, package maps, and the exports field.

A GPS route resolving ./utils.js to file:///app/src/utils.js through a city of folders

Specifier Kinds

The string after from is the specifier. Its first characters decide which resolution path runs. There are five kinds, and they behave differently:

Relative

import utils from './utils.js';
import config from '../config.js';

Resolved against the URL of the importing module, using URL resolution rules rather than filesystem rules.

Root-Relative

import { render } from '/lib/render.js';

Resolved against the origin, not the importing file. Moving the importer does not change where this points.

Absolute URL

import lodash from 'https://esm.sh/[email protected]';
import worker from 'file:///opt/app/worker.js';

Used exactly as written. No lookup runs. Node.js accepts file:, node:, and data: URLs.

Bare

import express from 'express';
import debounce from 'lodash/debounce.js';
import { z } from '@scope/validators';

Carries no location at all. Something external has to supply one: an import map in the browser, a node_modules walk in Node.js.

Private (#)

import { connect } from '#db';

Resolved by the imports field of the importing package. Visible only inside that package.

Identity Is the Resolved URL

A module's identity is the full URL, including the query string and the hash. ./m.js and ./m.js?v=2 resolve to different URLs, so they load twice and each gets its own module state.

File Extension Rules

CommonJS guessed. It tried ./utils, then ./utils.js, then ./utils.json, then ./utils/index.js. ES Modules do not guess. In a browser every guess would be a wasted network round trip, so the specifier must name the file exactly:

Will Not Resolve

import utils from './utils';

Correct

import utils from './utils.js';

The extension in the specifier is part of the URL. It is not what decides how the file is parsed. Each host answers that question its own way:

  • Browsers use the response Content-Type. A file served as text/plain is rejected no matter what it is named.
  • Node.js uses the extension plus the nearest package.json. .mjs is always ESM, .cjs is always CommonJS, and .js follows the type field.
  • Import attributes override the guess entirely for non-JavaScript resources. See Import Attributes.

Directory Resolution

There is no directory index in ES Modules. A specifier that names a folder does not fall back to index.js, with or without a trailing slash:

// Directory layout
// src/utils/index.js
// src/utils/date.js

import u from './utils';       // fails - no extension, no index fallback
import u from './utils/';      // fails - directories are not modules
import u from './utils/index.js';  // resolves

Bare specifiers are the exception, and only because a package declares its own entry points. import 'lodash-es' works because the package's exports field names a file for the . subpath. The resolver reads that declaration; it never scans the directory.

Trailing Slashes Are Prefixes

A trailing slash in an import map key or an exports pattern means string prefix matching, not directory listing. The remainder of the specifier is appended to the target, so "lodash/" maps lodash/debounce.js and nothing is enumerated.

The Lookup Order

Both hosts run an ordered algorithm and stop at the first match. Knowing the order tells you exactly which step failed when an import throws.

In the Browser

  1. If the specifier parses as a URL, or starts with /, ./, or ../, resolve it against the importing module's URL and stop.
  2. Otherwise it is bare. Check the import map scopes whose path prefix matches the importing module, most specific first.
  3. Fall through to the top-level imports table. An exact key beats a trailing-slash prefix key, and among prefix keys the longest one wins.
  4. No match throws a TypeError before any request is made. A failed resolution is never a 404.

In Node.js

  1. Relative and absolute specifiers resolve against the parent URL, then the file must exist. No extension is added.
  2. A # prefix resolves through the imports field of the nearest package.json.
  3. Built-in names such as node:fs return the built-in module.
  4. Any other bare specifier walks node_modules upward from the importing file to the filesystem root, taking the first directory that contains the package.
  5. Inside that package, exports selects the subpath and the matching condition. Only a package with no exports field falls back to main.
// Importing 'zod' from /app/src/api/user.js
// Node checks, in order:
/app/src/api/node_modules/zod
/app/src/node_modules/zod
/app/node_modules/zod        <-- found, read its exports field
/node_modules/zod

Resolution Runs Once Per URL

Both hosts key their module cache on the resolved URL. Ten files importing lodash produce one resolution result and one module instance. Two specifiers that resolve to different URLs produce two instances, even when the file content is identical.

Self-Referencing Imports

The imports field in package.json defines private mappings for the package itself, using the # prefix:

// package.json
{
  "imports": {
    "#utils/*": "./src/utils/*.js",
    "#db": {
      "node": "./src/db-node.js",
      "default": "./src/db-browser.js"
    }
  }
}

// In your code - clean imports without relative paths
import { format } from '#utils/format';
import { connect } from '#db';

A package can also import itself by its own name. If package.json declares "name": "my-lib" and an exports field, then import 'my-lib/utils' works from inside the package. Tests then exercise the same public entry points consumers get, instead of reaching into src/ through relative paths.

Benefits:

  • Eliminates long relative paths (../../../utils)
  • Supports conditional resolution (node vs browser)
  • Works in every maintained Node.js release with no tooling
  • Cannot be imported by other packages (private)

Import Maps in One Paragraph

An import map is the browser's answer to bare specifiers. A <script type="importmap"> block maps package names to URLs, and scopes lets different paths resolve the same name differently. Import maps are Baseline: Chrome 89+, Edge 89+, Firefox 108+, and Safari 16.4+ all ship them.

Import Maps covers the full syntax, prefix mapping, CDN patterns, multiple maps, and integrity metadata.

Package Maps: Node's Answer

Node.js does not implement import maps, but it now has its own take on the same idea. Package maps, added in Node 26.4 and backported to 24.20 on 08-26-2026, resolve bare specifiers from a JSON table instead of by walking node_modules. Enable them with --experimental-package-map=./package-map.json; the feature is experimental.

{
  "packages": {
    "app": {
      "url": "./src/",
      "dependencies": { "lodash": "lodash-4" }
    },
    "lodash-4": { "url": "./vendor/lodash/" }
  }
}

The point is that resolution runs off static data without touching the file system, which is what makes it useful for monorepos that would otherwise need symlinks or hoisting, and for blocking phantom dependencies: a specifier a package never declared throws MODULE_NOT_FOUND rather than quietly resolving. Once a package is located, the ordinary algorithm takes over, so exports still applies.

The exports Field in One Paragraph

A package's exports field is the input the resolver reads once it has found the package directory. It declares which subpaths exist, blocks deep imports into files you did not publish, and selects a different file per condition such as import, require, or types. Conditions are checked in the order they are written, so the first match wins.

Publishing covers conditional exports, dual packages, subpath patterns, and the ordering rules in full.

What Happens After Resolution

Resolution produces a URL. The loader then runs four phases against it, and every imported URL in the graph goes through the same sequence:

1. Construction (Parsing)

Fetch and parse the file into a Module Record, then resolve its own imports and repeat. Each URL is fetched once.

2. Instantiation (Linking)

Allocate memory for all exports. Connect imports to their corresponding exports (live bindings). No code is executed yet.

3. Evaluation (Execution)

Execute module code to fill in the allocated memory with actual values. Each module is evaluated exactly once, in dependency order.

4. Caching

The evaluated module is stored in the Module Map. Any future import of the same URL returns the cached module instance.

A resolution failure aborts before phase one, which is why the error names a specifier rather than a file. A 404 aborts during phase one and names a URL. That distinction is the fastest way to tell a bad map entry from a bad deploy.

Frequently Asked Questions

Continue Learning