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.
Code
// 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.tsUnder 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.