import.meta.resolve Locates Module Specifiers

Locate module specifiers with import.meta.resolve, check node and file URL results, and resolve a relative asset path without reading the file.

TypescriptConfig Management

Code

typescriptsnippet
17 lines
const builtin = "node:path";
const resolvedBuiltin = import.meta.resolve(builtin);
console.log("builtin:", builtin);
console.log("resolved:", resolvedBuiltin);
console.log("is node url:", resolvedBuiltin.startsWith("node:"));

const relative = import.meta.resolve("./fixtures/users.json");
console.log("relative:", relative);
console.log("ends with asset:", relative.endsWith("fixtures/users.json"));

const self = import.meta.resolve(import.meta.url);
console.log("self is file url:", self.startsWith("file:"));

const specifiers = ["node:fs", "node:url", "node:os"];
const resolved = specifiers.map((specifier) => import.meta.resolve(specifier));
console.log("resolved count:", resolved.length);
console.log("all node:", resolved.every((url) => url.startsWith("node:")));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

builtin: node:path
resolved: node:path
is node url: true
relative: file:///C:/Users/GUANGM%7E1/AppData/Local/Temp/devex-run-EPIZOU/fixtures/users.json
ends with asset: true
self is file url: true
resolved count: 3
all node: true

How it works

Top-level bindings builtin, resolvedBuiltin, relative, self hold the demo state — nothing sits inside a function scope.

What to watch for

  • node:path is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Using it

The run emits 8 labeled sections — builtin:, resolved:, is node url:, relative:, ends with asset:, self is file url:, resolved count:, all node: — one per step.

Key statements

const resolved = specifiers.map((specifier) => import.meta.resolve(specifier));

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.