Sub topic 5
Module Specifiers: Relative Paths, Bare Names, and File Extensions
This chapter assumes you know how to write import and export declarations, which earlier chapters covered. You should also be able to run a script with Node.js and open a page in a browser. The topic here is the string that follows from. It looks like a file path, but the rules for turning it into an actual file are stricter than most people expect. Those rules are the source of many "module not found" errors.
What a Specifier Is
A module specifier is the string literal in an import or export ... from declaration that names the module to load.
import { area } from './math.js'; // specifier: './math.js'
import debounce from 'lodash-es/debounce.js'; // specifier: 'lodash-es/debounce.js'
import { readFile } from 'node:fs/promises'; // specifier: 'node:fs/promises'
export * from '../shared/units.js'; // specifier: '../shared/units.js'In a static declaration the specifier must be a plain string literal. A variable, a template literal with substitutions, or string concatenation is a syntax error, because the engine reads every specifier before any code runs:
const name = './math.js';
// import { area } from name; // SyntaxError
// import { area } from `./${'math'}.js`; // SyntaxErrorIf you need a computed specifier, use dynamic import(), which a later chapter covers.
The host environment turns a specifier into a full URL. The host is the browser or Node.js, since the JavaScript language specification leaves resolution to it. Both hosts treat a specifier as a URL reference, not as an operating-system path. That one fact explains most of the rules below.
The Kinds of Specifiers
| Kind | Example | Browser | Node.js (ESM) |
|---|---|---|---|
| Relative | `./math.js`, `../lib/a.js` | Resolved against the importing module's URL | Resolved against the importing module's URL |
| Absolute path | `/src/math.js` | Resolved against the page's origin | Treated as a `file:` path from the filesystem root, rarely what you want |
| Full URL | `https://cdn.example.com/x.js`, `file:///app/x.js`, `data:...` | `https:` and `data:` allowed | `file:`, `data:`, and `node:` allowed. `https:` is not allowed by default |
| Bare | `lodash-es`, `lodash-es/debounce.js` | Error unless an import map defines it | Looked up in `node_modules` using the package's `exports` |
| Built-in | `node:fs`, `fs` | Not available | Resolves to the Node.js core module |
A relative specifier must start with ./, ../, or /. Writing math.js without the leading ./ does not mean "the file next to me." It makes a bare specifier, and the host then looks for a package called math.js.
Relative to the Module, Not the Working Directory
A relative specifier resolves against the URL of the module that contains the import. It does not resolve against the current working directory or the HTML page, unless the import is in an inline script. You can reproduce the algorithm with the URL constructor, which applies the same rules:
// resolve.mjs (run with: node resolve.mjs)
const importer = 'https://example.com/app/features/chart/main.js';
const cases = ['./math.js', '../shared/units.js', '/vendor/lib.js', 'math.js'];
for (const spec of cases) {
const isRelative = /^(\.{1,2})?\//.test(spec);
console.log(
spec.padEnd(22),
isRelative ? new URL(spec, importer).href : '(bare specifier: not resolved as a path)'
);
}Output:
./math.js https://example.com/app/features/chart/math.js
../shared/units.js https://example.com/app/features/shared/units.js
/vendor/lib.js https://example.com/vendor/lib.js
math.js (bare specifier: not resolved as a path)Because resolution follows the importer, moving a file breaks its relative imports and the relative imports that point to it. Moving the folder that holds both files does not break the import between them.
File Extensions Are Not Optional
Browsers fetch exactly the URL you give them. Node.js in ES module mode does the same thing on disk. Neither host tries .js, .mjs, or /index.js for you.
import { area } from './math'; // fails: there is no file named "math"
import { area } from './math.js'; // works
import * as shapes from './shapes'; // fails in Node.js ESM: directory import
import * as shapes from './shapes/index.js'; // worksIn Node.js the first line produces ERR_MODULE_NOT_FOUND, and the third produces ERR_UNSUPPORTED_DIR_IMPORT. In a browser the server usually returns a 404, or it returns an HTML fallback page, which then fails the MIME type check.
TypeScript is a special case. With "moduleResolution": "nodenext", you write ./math.js in a .ts file even though the source file is math.ts. The specifier names the file that will exist at run time.
Bare Specifiers
A bare specifier names a package instead of a location. It can be just the package name (lodash-es) or a package name followed by a subpath (lodash-es/debounce.js). Scoped packages work the same way: @scope/pkg/sub.
- Node.js walks up from the importing file's directory and checks each
node_modulesfolder for the package. Once it finds the package, it reads theexportsfield in the package'spackage.json, which controls which subpaths can be imported. A subpath that is not listed fails withERR_PACKAGE_PATH_NOT_EXPORTED, even when the file exists. - Browsers have no
node_moduleslookup. A bare specifier throwsTypeError: Failed to resolve module specifier "lodash-es"unless an import map maps it to a URL. The next chapter shows how to set one up.
Node.js core modules accept the node: prefix (node:fs, node:path). Use the prefix. It makes clear that the module is built in, and a package in node_modules with the same name can never shadow it.
The Resolved URL Is the Module's Identity
A host loads each resolved URL once and reuses that module instance for every later import. Two specifiers that resolve to the same URL share one instance. Specifiers that differ after resolution create separate instances:
import { count } from './counter.js';
import { count as again } from '../src/counter.js'; // same file, same URL: same instance
import * as fresh from './counter.js?v=2'; // different URL: a second instanceThis matters for modules that hold state. A query string, or a mix of file: URLs and symlinked paths, can quietly give you two copies of a module that is supposed to be a singleton. Case also matters. On a case-insensitive filesystem, ./Math.js and ./math.js can both load, but they are separate modules, and the code fails on Linux.
Common Errors at a Glance
| Symptom | Likely cause | Fix |
|---|---|---|
| `Failed to resolve module specifier "utils.js"` | Missing `./` turned the path into a bare specifier | Write `./utils.js` |
| `ERR_MODULE_NOT_FOUND` for `./math` | Missing extension | Write `./math.js` |
| `ERR_UNSUPPORTED_DIR_IMPORT` | Imported a folder | Import `./folder/index.js` |
| `ERR_PACKAGE_PATH_NOT_EXPORTED` | Subpath not listed in the package's `exports` | Use a subpath the package exports |
| Works on macOS, fails in CI | Case mismatch in the file name | Match the file name's case exactly |
Exercise
The module at https://site.test/app/pages/home.js contains import { nav } from '../components/nav.js'; and import { fmt } from 'format.js';. What URL does each specifier resolve to in a browser with no import map, and what happens?
Show answer
'../components/nav.js' resolves against the importing module's URL to https://site.test/app/components/nav.js, and the browser fetches it. 'format.js' does not start with ./, ../ or /, so it is a bare specifier. With no import map, the browser throws a TypeError ("Failed to resolve module specifier") and the module graph fails to load. Writing './format.js' would load https://site.test/app/pages/format.js.
Exercise
A Node.js project with "type": "module" contains import { area } from './geometry';, where geometry is a folder that holds index.js. Explain why this fails and give the corrected specifier.
Show answer
Node.js ES module resolution does not add file extensions or look for directory index files. Importing the folder fails with ERRUNSUPPORTEDDIR_IMPORT. The fix is import { area } from './geometry/index.js';.
Exercise
A module imports './store.js' in one file and './store.js?debug' in another. Both point to the same file on disk. How many instances of store.js run, and why?
Show answer
Two instances run. The host treats each resolved URL as a separate module, and the query string makes the URLs different. Each instance evaluates on its own and keeps its own state.