Skip to content

Commit

Permalink
fix: importmap should insert before module preload link
Browse files Browse the repository at this point in the history
  • Loading branch information
fi3ework committed Dec 27, 2022
1 parent 13ac37d commit 008c639
Showing 1 changed file with 19 additions and 4 deletions.
23 changes: 19 additions & 4 deletions packages/vite/src/node/plugins/html.ts
Expand Up @@ -50,6 +50,8 @@ const importMapRE =
/[ \t]*<script[^>]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is
const moduleScriptRE =
/[ \t]*<script[^>]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i
const modulePreloadLinkRE =
/[ \t]*<link[^>]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload).*?\/>/is

export const isHTMLProxy = (id: string): boolean => htmlProxyRE.test(id)

Expand Down Expand Up @@ -910,20 +912,33 @@ export function preImportMapHook(
}

/**
* Move importmap before the first module script
* Move importmap before the first module script and modulepreload link
*/
export function postImportMapHook(): IndexHtmlTransformHook {
return (html) => {
if (!moduleScriptRE.test(html)) return

let importMap: string | undefined

html = html.replace(importMapRE, (match) => {
importMap = match
return ''
})
if (importMap) {
html = html.replace(moduleScriptRE, (match) => `${importMap}\n${match}`)
}

if (!importMap) return html

const firstModuleScriptIndex = html.match(moduleScriptRE)?.index
const firstModulePreloadIndex = html.match(modulePreloadLinkRE)?.index

const ImportMapInsertionIndex = Math.min(
firstModuleScriptIndex ?? Infinity,
firstModulePreloadIndex ?? Infinity,
)
if (ImportMapInsertionIndex === Infinity) return html

html = `${html.slice(0, ImportMapInsertionIndex)}${importMap}\n${html.slice(
ImportMapInsertionIndex,
)}`

return html
}
Expand Down

0 comments on commit 008c639

Please sign in to comment.