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 9eaae2d
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 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,7 +912,7 @@ 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) => {
Expand All @@ -921,9 +923,20 @@ export function postImportMapHook(): IndexHtmlTransformHook {
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 9eaae2d

Please sign in to comment.