Skip to content

Commit

Permalink
fix(html): fix css disorder when building multiple entry html (#19143)
Browse files Browse the repository at this point in the history
  • Loading branch information
thy486 authored Feb 4, 2025
1 parent 3f5f2bd commit e7b4ba3
Showing 1 changed file with 48 additions and 25 deletions.
73 changes: 48 additions & 25 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
},

async generateBundle(options, bundle) {
const analyzedChunk = new Map<OutputChunk, number>()
const analyzedImportedCssFiles = new Map<OutputChunk, string[]>()
const inlineEntryChunk = new Set<string>()
const getImportedChunks = (
chunk: OutputChunk,
Expand Down Expand Up @@ -777,39 +777,62 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
},
})

const getCssTagsForChunk = (
chunk: OutputChunk,
const toStyleSheetLinkTag = (
file: string,
toOutputPath: (filename: string) => string,
seen: Set<string> = new Set(),
): HtmlTagDescriptor[] => {
const tags: HtmlTagDescriptor[] = []
if (!analyzedChunk.has(chunk)) {
analyzedChunk.set(chunk, 1)
chunk.imports.forEach((file) => {
const importee = bundle[file]
if (importee?.type === 'chunk') {
tags.push(...getCssTagsForChunk(importee, toOutputPath, seen))
}
})
): HtmlTagDescriptor => ({
tag: 'link',
attrs: {
rel: 'stylesheet',
crossorigin: true,
href: toOutputPath(file),
},
})

const getCssFilesForChunk = (
chunk: OutputChunk,
seenChunks: Set<string> = new Set(),
seenCss: Set<string> = new Set(),
): string[] => {
if (seenChunks.has(chunk.fileName)) {
return []
}
seenChunks.add(chunk.fileName)

if (analyzedImportedCssFiles.has(chunk)) {
const files = analyzedImportedCssFiles.get(chunk)!
const additionals = files.filter((file) => !seenCss.has(file))
additionals.forEach((file) => seenCss.add(file))
return additionals
}

const files: string[] = []
chunk.imports.forEach((file) => {
const importee = bundle[file]
if (importee?.type === 'chunk') {
files.push(...getCssFilesForChunk(importee, seenChunks, seenCss))
}
})
analyzedImportedCssFiles.set(chunk, files)

chunk.viteMetadata!.importedCss.forEach((file) => {
if (!seen.has(file)) {
seen.add(file)
tags.push({
tag: 'link',
attrs: {
rel: 'stylesheet',
crossorigin: true,
href: toOutputPath(file),
},
})
if (!seenCss.has(file)) {
seenCss.add(file)
files.push(file)
}
})

return tags
return files
}

const getCssTagsForChunk = (
chunk: OutputChunk,
toOutputPath: (filename: string) => string,
) =>
getCssFilesForChunk(chunk).map((file) =>
toStyleSheetLinkTag(file, toOutputPath),
)

for (const [normalizedId, html] of processedHtml(this)) {
const relativeUrlPath = normalizePath(
path.relative(config.root, normalizedId),
Expand Down

0 comments on commit e7b4ba3

Please sign in to comment.