An Import Maps parser and resolver, with features:
- Parse import maps from JSON/HTML
- Resolve specifiers to URLs using import map matching rules
- Add npm/jsr/github modules from esm.sh CDN
- Generate
integrityentries for added modules
npm i @esm.sh/import-mapCreate an import map instance:
import { ImportMap } from "@esm.sh/import-map";
const im = new ImportMap();You can also initialize from a raw object:
const im = new ImportMap("https://example.com/app/", {
config: { cdn: "https://esm.sh", target: "es2022" },
imports: { react: "https://esm.sh/react@19.2.4/es2022/react.mjs" },
scopes: {
"https://esm.sh/": {
scheduler: "https://esm.sh/scheduler@0.27.0/es2022/scheduler.mjs",
},
},
integrity: {
"https://esm.sh/react@19.2.4/es2022/react.mjs": "sha384-...",
},
});Parse an import map from JSON text.
Preserves and validates config, imports, scopes, and integrity.
import { parseFromJson } from "@esm.sh/import-map";
const im = parseFromJson(`{
"imports": {
"react": "https://esm.sh/react@19.2.4/es2022/react.mjs"
}
}`);Parse the first <script type="importmap"> from HTML (browser environment). Returns an empty import map if no importmap script tag is found.
import { parseFromHtml } from "@esm.sh/import-map";
const im = parseFromHtml(`<script type="importmap">
{
"imports": {
"react": "https://esm.sh/react@19.2.4/es2022/react.mjs"
}
}
</script>`);Note: This function requires a browser environment.
The addImport method fetches package metadata from esm.sh CDN and adds an entry (plus relevant deps) to the map.
Supported specifiers include:
- npm:
react@19.2.4,react-dom@19/client - jsr:
jsr:@std/fs@1.0.0 - github:
gh:owner/repo@tag
Behavior highlights:
- adds top-level entries into
imports - adds nested deps into
scopeswhen needed - cleans up empty scopes
- updates
integrityunlessnoSRIistrue
import { ImportMap } from "@esm.sh/import-map";
const im = new ImportMap();
await im.addImport("react-dom@19/client");The resolve method resolves a specifier using import-map matching rules:
const [url, ok] = im.resolve("react", "file:///app/main.ts");Returns [resolvedUrl, true] when matched, otherwise [originalSpecifier, false].
The raw getter returns a clean, key-ordered import-map object (ImportMapRaw):
const raw = im.raw;
// {
// config?: { ... },
// imports?: { ... },
// scopes?: { ... },
// integrity?: { ... },
// }function isSupportImportMap() returns whether the current browser supports import maps.
import { isSupportImportMap } from "@esm.sh/import-map";
const supported = isSupportImportMap();bun test
bun run buildMIT