Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: sequential injection of tags in transformIndexHtml (#5851) #6901

Merged
merged 3 commits into from Jun 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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