withImportMap

tcmts.cli.web.withImportMap · #ghiv6mia · term · runs anywhere

A page with an import map: chunks import each other by names that don't change with their content, and the map, in the page (which is never cached), says which file each is now. So a chunk that changed doesn't change the chunks that import it. Before any module script, as browsers require.

export function withImportMap(html: string, map: string): string {
  const tag = `<script type="importmap">${map.trim().replace(/<\//g, "<\\/")}</script>`;
  const at = html.search(/<script type="module"|<link rel="modulepreload"/);
  return at < 0
    ? html.replace("</head>", `${tag}\n</head>`)
    : `${html.slice(0, at)}${tag}\n    ${html.slice(at)}`;
}

used by