From 649c7f60525ec4755f147312475cb473b80d7d5e Mon Sep 17 00:00:00 2001 From: Menci Date: Wed, 15 Jun 2022 02:13:46 +0800 Subject: [PATCH] fix: sequential injection of tags in transformIndexHtml (#5851) (#6901) Co-authored-by: sapphi-red --- packages/vite/src/node/plugins/html.ts | 34 ++++++++++++-------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 9d06d6e168f2e1..a66a6288f8e8c2 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -767,11 +767,6 @@ export async function applyHtmlTransforms( hooks: IndexHtmlTransformHook[], ctx: IndexHtmlTransformContext ): Promise { - 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) { @@ -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) @@ -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 @@ -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)) { @@ -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)) {