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

feat: add headTagInsertCheck warning #16555

Merged
merged 2 commits into from
May 29, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
partialEncodeURIPath,
processSrcSet,
removeLeadingSlash,
unique,
urlCanParse,
} from '../utils'
import type { ResolvedConfig } from '../config'
Expand Down Expand Up @@ -1265,6 +1266,42 @@ export function resolveHtmlTransforms(
return [preHooks, normalHooks, postHooks]
}

// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/head#see_also
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
const elementsAllowedInHead = new Set([
'title',
'base',
'link',
'style',
'meta',
'script',
'noscript',
'template',
])

function headTagInsertCheck(
tags: HtmlTagDescriptor[],
ctx: IndexHtmlTransformContext,
) {
if (!tags.length) return
const { logger } = ctx.server?.config || {}
const disallowedTags = tags.filter(
(tagDescriptor) => !elementsAllowedInHead.has(tagDescriptor.tag),
)

if (disallowedTags.length) {
const dedupedTags = unique(
disallowedTags.map((tagDescriptor) => `<${tagDescriptor.tag}>`),
)
logger?.warn(
colors.yellow(
colors.bold(
`[${dedupedTags.join(',')}] can not be used inside the <head> Element, please check the 'injectTo' value`,
),
),
)
}
}

export async function applyHtmlTransforms(
html: string,
hooks: IndexHtmlTransformHook[],
Expand Down Expand Up @@ -1306,7 +1343,7 @@ export async function applyHtmlTransforms(
;(headPrependTags ??= []).push(tag)
}
}

headTagInsertCheck([...(headTags || []), ...(headPrependTags || [])], ctx)
if (headPrependTags) html = injectToHead(html, headPrependTags, true)
if (headTags) html = injectToHead(html, headTags)
if (bodyPrependTags) html = injectToBody(html, bodyPrependTags, true)
Expand Down