Skip to content

Commit

Permalink
fix: sequential injection of tags in transformIndexHtml (#5851) (#6901)
Browse files Browse the repository at this point in the history
Co-authored-by: sapphi-red <green@sapphi.red>
  • Loading branch information
Menci and sapphi-red committed Jun 14, 2022
1 parent d7beaeb commit 649c7f6
Showing 1 changed file with 15 additions and 19 deletions.
34 changes: 15 additions & 19 deletions packages/vite/src/node/plugins/html.ts
Expand Up @@ -767,11 +767,6 @@ export async function applyHtmlTransforms(
hooks: IndexHtmlTransformHook[],
ctx: IndexHtmlTransformContext
): Promise<string> {
const headTags: HtmlTagDescriptor[] = []
const headPrependTags: HtmlTagDescriptor[] = []
const bodyTags: HtmlTagDescriptor[] = []
const bodyPrependTags: HtmlTagDescriptor[] = []

for (const hook of hooks) {
const res = await hook(html, ctx)
if (!res) {
Expand All @@ -787,6 +782,12 @@ export async function applyHtmlTransforms(
html = res.html || html
tags = res.tags
}

const headTags: HtmlTagDescriptor[] = []
const headPrependTags: HtmlTagDescriptor[] = []
const bodyTags: HtmlTagDescriptor[] = []
const bodyPrependTags: HtmlTagDescriptor[] = []

for (const tag of tags) {
if (tag.injectTo === 'body') {
bodyTags.push(tag)
Expand All @@ -798,21 +799,12 @@ export async function applyHtmlTransforms(
headPrependTags.push(tag)
}
}
}
}

// inject tags
if (headPrependTags.length) {
html = injectToHead(html, headPrependTags, true)
}
if (headTags.length) {
html = injectToHead(html, headTags)
}
if (bodyPrependTags.length) {
html = injectToBody(html, bodyPrependTags, true)
}
if (bodyTags.length) {
html = injectToBody(html, bodyTags)
html = injectToHead(html, headPrependTags, true)
html = injectToHead(html, headTags)
html = injectToBody(html, bodyPrependTags, true)
html = injectToBody(html, bodyTags)
}
}

return html
Expand Down Expand Up @@ -859,6 +851,8 @@ function injectToHead(
tags: HtmlTagDescriptor[],
prepend = false
) {
if (tags.length === 0) return html

if (prepend) {
// inject as the first element of head
if (headPrependInjectRE.test(html)) {
Expand Down Expand Up @@ -893,6 +887,8 @@ function injectToBody(
tags: HtmlTagDescriptor[],
prepend = false
) {
if (tags.length === 0) return html

if (prepend) {
// inject after body open
if (bodyPrependInjectRE.test(html)) {
Expand Down

0 comments on commit 649c7f6

Please sign in to comment.