resolve-esm

Shim for `import.meta.resolve`

Usage no npm install needed!

<script type="module">
  import resolveEsm from 'https://cdn.skypack.dev/resolve-esm';
</script>

README

resolve-esm

Shim for import.meta.resolve.

npm downloads install size license node types vulnerabilities CodeQL Open in VSCode

import.meta.resolve is currently "Experimental", and is only available with the --experimental-import-meta-resolve command flag enabled.
This module provides functions equivalent to import.meta.resolve without the experimental flag.

Differences from similar modules

This module is just a "wrapper" that internally calls the original import.meta.resolve and has no resolve logic of its own.
Therefore, it will be easy to follow if the original specification changes, and easy to migrate when the original becomes "Stable" in the future.

Usage

npm i resolve-esm
import { importMetaResolve } from 'resolve-esm';

Note:
This module is only available in ES Module.

await importMetaResolve('./other.mjs');
// => file:///path/to/__dirname/other.mjs

await importMetaResolve('./other.mjs', 'file:///different/path/parent.mjs');
// => file:///different/path/other.mjs

await importMetaResolve('dependency');
// => file:///path/to/node_modules/dependency/main.mjs

await importMetaResolve('dependency', 'file:///different/path/parent.mjs');
// => file:///different/path/node_modules/dependency/main.mjs

await importMetaResolve('fs');
// => node:fs

API

importMetaResolve

Resolve a (single) module specifier.

declare function importMetaResolve(specifier: string, parent?: string | URL): Promise<string>;

Parameters

  • specifier (Type: string)
    • The module specifier to resolve relative to parent.
  • parent (Type: string | URL | undefined)
    • The absolute parent module URL to resolve from.
    • If none is specified, the value of import.meta.url is used as the default.

Returns

A Promise that resolves to a module URL string.

importMetaResolveAll

Resolve multiple module specifiers with same parent.

declare function importMetaResolveAll(specifiers: readonly string[], parent?: string | URL): Promise<string[]>;

Parameters

  • specifiers (Type: string[])
    • The array of module specifiers to resolve relative to parent.
  • parent (Type: string | URL | undefined)
    • The absolute parent module URL to resolve from.
    • If none is specified, the value of import.meta.url is used as the default.

Returns

A Promise that resolves to an array of module URL strings.

What is this function for?

For internal processing reasons, it is more efficient than calling Promise.all() on your own.

  • works, but inefficient
    const results = await Promise.all([
        importMetaResolve('specifier1'),
        importMetaResolve('specifier2'),
        importMetaResolve('specifier3'),
    ]);
    
  • better
    const results = await importMetaResolveAll([
        'specifier1',
        'specifier2',
        'specifier3',
    ]);