import.meta Resolves Module URLs

Read import.meta.url, resolve a sibling fixture with new URL, and inspect the resulting file URL and query parameters.

TypescriptConfig Management

Code

typescriptsnippet
15 lines
// import.meta exposes metadata about the current module.
const moduleUrl = new URL(import.meta.url);
const fixture = new URL('./fixtures/users.json', import.meta.url);

console.log('module path:', moduleUrl.pathname);
console.log('protocol:', moduleUrl.protocol);
console.log('fixture:', fixture.href);

fixture.searchParams.set('page', '2');
fixture.searchParams.set('limit', '50');

console.log('paged:', fixture.href);
console.log('query:', fixture.searchParams.toString());
console.log('is file url:', moduleUrl.protocol === 'file:');
console.log('module file:', moduleUrl.pathname.split('/').pop() ?? 'unknown');

Output

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

module path: /C:/Users/GUANGM%7E1/AppData/Local/Temp/devex-run-xOqukF/snippet.ts
protocol: file:
fixture: file:///C:/Users/GUANGM%7E1/AppData/Local/Temp/devex-run-xOqukF/fixtures/users.json
paged: file:///C:/Users/GUANGM%7E1/AppData/Local/Temp/devex-run-xOqukF/fixtures/users.json?page=2&limit=50
query: page=2&limit=50
is file url: true
module file: snippet.ts

Under the hood

Top-level bindings moduleUrl, fixture hold the demo state — nothing sits inside a function scope.

Applying it

The run emits 7 labeled sections — module path:, protocol:, fixture:, paged:, query:, is file url:, module file: — one per step.

Statements that matter

const fixture = new URL('./fixtures/users.json', import.meta.url);
const moduleUrl = new URL(import.meta.url);
fixture.searchParams.set('limit', '50');

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. Its state lives in module-level bindings: `moduleUrl`, `fixture`.