Sub topic 8
Specifiers, Template Literals, and Resolution Rules
This chapter assumes you already know static import/export syntax, async/await, and the basic import() call covered earlier. It looks at the string you pass to import(): what forms it can take, how the runtime turns it into a concrete file or URL, and what changes when you build that string at runtime.
What a Specifier Is
A module specifier is the string that names a module, such as './chart.js' in import('./chart.js'). The runtime never loads the specifier directly. It first resolves it to an absolute URL. That URL becomes the module's identity, and fetching, evaluating, and caching all happen against it.
Specifiers come in three kinds:
| Kind | Example | Browser (no import map) | Node.js ESM |
|---|---|---|---|
| Relative | `'./util.js'`, `'../lib/a.js'` | Resolved against the importing module's URL | Resolved against the importing file's URL |
| Absolute URL | `'https://cdn.example.com/x.js'`, `'file:///app/x.js'` | Fetched as is (subject to CORS) | `file:`, `data:`, and `node:` allowed; `https:` not supported by default |
| Bare | `'lodash-es'`, `'@scope/pkg/sub'` | Error unless an import map defines it | Looked up in `node_modules` using `package.json` `exports` |
A relative specifier has to start with ./, ../, or /. The string 'util.js' is a bare specifier, not a relative one. Mixing these up is a common source of "failed to resolve" errors.
Resolution Is Relative to the Importing Module
import() resolves relative specifiers against the URL of the module that contains the call. The current working directory and the HTML page's location do not affect it. A dynamic import inside src/app/main.js behaves like a static import would in that same file:
// src/app/main.js
const util = await import('../lib/util.js'); // always src/lib/util.js
console.log(import.meta.url); // file:///.../src/app/main.jsThis also holds when you move the call into a helper. If src/helpers/load.js exports function load(p) { return import(p); }, then load('./x.js') resolves against src/helpers/, not against the caller's folder. Each import() call site captures its own module as the referrer.
The browser has one exception. In inline classic scripts and in event handler attributes there is no module URL, so import() resolves against the document's base URL.
Seeing the Resolved URL with import.meta.resolve
import.meta.resolve() returns the URL a specifier would resolve to, without loading anything. It is synchronous in browsers and in Node.js 20.6 and later.
// src/app/main.js
console.log(import.meta.resolve('./util.js'));
// file:///.../src/app/util.js
console.log(import.meta.resolve('node:fs'));
// node:fsFor bare specifiers, Node.js runs the full package lookup and returns the file URL of the entry point. This is a quick way to debug "why did it load that file?" questions.
How Resolution Works
The resolution steps are similar in both environments, with different rules for bare specifiers.
Node.js rules that surprise people
Node.js's ESM resolver is stricter than require():
- File extensions are mandatory.
import('./util')fails withERR_MODULE_NOT_FOUNDeven ifutil.jsexists. - No directory index.
import('./lib')does not findlib/index.js. It fails withERR_UNSUPPORTED_DIR_IMPORT. exportsis enforced. If a package'spackage.jsonhas anexportsfield, any subpath not listed there is blocked withERR_PACKAGE_PATH_NOT_EXPORTED, even when the file exists on disk.- Conditions are applied.
import()matches the"import"condition inexports.require()matches"require". The same package name can therefore resolve to different files for the two loaders.
Browser bare specifiers need an import map
Browsers have no node_modules. You map bare names to URLs with an import map placed before any module script:
<script type="importmap">
{
"imports": {
"lodash-es": "https://cdn.jsdelivr.net/npm/[email protected]/lodash.js",
"app/": "/static/app/"
}
}
</script>
<script type="module">
const { debounce } = await import('lodash-es');
const { start } = await import('app/start.js'); // -> /static/app/start.js
start(debounce);
</script>Entries ending in / map a whole prefix. Import maps apply to static and dynamic imports alike.
Computed Specifiers and Template Literals
Static import declarations need a string literal. import() accepts any expression. The runtime converts the value to a string and then resolves it. That is how you build locale or plugin paths:
const lang = navigator.language.slice(0, 2);
const { default: messages } = await import(`./locales/${lang}.js`);Resolution happens after evaluation. A bad computed path does not throw synchronously. The returned promise rejects with a TypeError (browser) or an error carrying a Node.js code, and the error handling from the previous chapter catches it.
Validate before you interpolate
A computed specifier is a code-loading decision. If any part comes from a URL parameter, user input, or a config file you do not control, an attacker can steer it: lang = '../admin/debug' walks out of the locales folder, and in Node.js a full data: URL or absolute file: URL could load arbitrary code. Restrict the input to a known set:
// i18n.js
const SUPPORTED = new Set(['en', 'fr', 'de']);
export async function loadLocale(lang) {
if (!SUPPORTED.has(lang)) {
throw new RangeError(`Unsupported locale: ${lang}`);
}
const mod = await import(`./locales/${lang}.js`);
return mod.default;
}An allowlist also helps with bundling. A template literal with a fixed prefix and suffix, such as ` ./locales/${lang}.js , gives build tools a pattern they can expand. A fully dynamic import(userPath)` does not. The next chapter covers how bundlers handle each case.
Turning file paths into URLs in Node.js
Specifiers are URLs, not file system paths. On POSIX systems an absolute path like /home/me/plugin.js happens to work. On Windows, C:\plugins\a.js is read as a URL with the scheme c: and fails. Convert paths explicitly:
// load-plugin.mjs — run with: node load-plugin.mjs ./plugins/hello.mjs
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const pluginPath = path.resolve(process.argv[2]); // relative to cwd, on purpose
const plugin = await import(pathToFileURL(pluginPath).href);
console.log(Object.keys(plugin));This is the right way to load a path relative to the current working directory. A bare import(process.argv[2]) would resolve relative to load-plugin.mjs, or be treated as a bare package name.
The Resolved URL Is the Cache Key
The module map caches instances by resolved URL. The specifier text does not matter, so two different strings that resolve to the same URL share one instance:
// src/app/main.js
const a = await import('./util.js');
const b = await import('../app/util.js');
console.log(a === b); // true: same resolved URLThe reverse also holds. Any difference in the URL, including the query string or fragment, produces a separate module that is fetched and evaluated again with its own state:
const v1 = await import('./counter.js?v=1');
const v2 = await import('./counter.js?v=2');
console.log(v1 === v2); // false: two independent instancesDevelopment tools sometimes use this for cache busting or hot reload. In Node.js, each new URL stays in memory for the life of the process, so reloading this way in a loop leaks memory.
Common Errors at a Glance
| Symptom | Likely cause | Fix |
|---|---|---|
| `Failed to resolve module specifier "x"` (browser) | Bare specifier with no import map entry | Add an import map entry or use `./x.js` |
| `ERR_MODULE_NOT_FOUND` | Missing extension or wrong relative base | Add `.js`, check which module contains the call |
| `ERR_UNSUPPORTED_DIR_IMPORT` | Importing a folder | Point at the file, e.g. `./lib/index.js` |
| `ERR_PACKAGE_PATH_NOT_EXPORTED` | Deep import not listed in `exports` | Use a documented subpath |
| `ERR_UNSUPPORTED_ESM_URL_SCHEME` | Windows path passed directly | Wrap with `pathToFileURL(...).href` |
Exercise
The file src/utils/loader.js exports export const load = (p) => import(p);. The file src/pages/home.js calls load('./widget.js'). The file src/pages/widget.js exists. Which file does Node.js try to load, and how would you fix the call without changing loader.js?
Show answer
It tries src/utils/widget.js, because import() resolves against the module that contains the call, which is loader.js. Fix it by passing an absolute URL from home.js: load(new URL('./widget.js', import.meta.url).href).
Exercise
A Node.js ESM app runs await import('./config') and await import('./models'), where config.js and models/index.js exist. Name the error each call produces and the corrected specifiers.
Show answer
'./config' fails with ERRMODULENOTFOUND because ESM requires the extension; use './config.js'. './models' fails with ERRUNSUPPORTEDDIRIMPORT because directory imports are not resolved; use './models/index.js'.
Exercise
A module calls import('./state.js') in one place and import('./state.js#reset') in another. Do both calls see the same exported state? Why?
Show answer
No. The fragment is part of the resolved URL, and the module map keys instances by URL, so the two calls create two separately evaluated module instances with independent state.