withStylesheetFiles

tcmts.cli.web.withStylesheetFiles · #u5yj4a7v · term · runs anywhere

A page naming the file each stylesheet its code only links to is now (__TCM_STYLESHEET_FILES__, by the name the code knows it by), as the import map names chunks: the page is never cached, so a stylesheet that changed doesn't change the code linking to it. Before any module script, which reads it as it loads.

export function withStylesheetFiles(html: string, files: Map<string, string>): string {
  if (!files.size) return html;
  const map = JSON.stringify(Object.fromEntries([...files].sort(([a], [b]) => (a < b ? -1 : 1))));
  const tag = `<script>var __TCM_STYLESHEET_FILES__ = ${map.replace(/</g, "\\u003c")};</script>`;
  const at = html.search(
    /<script type="importmap"|<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