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(html): fix css disorder when building multiple entry html #19143

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
61 changes: 45 additions & 16 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 analyzedChunk = new Map<OutputChunk, Set<string>>()
const inlineEntryChunk = new Set<string>()
const getImportedChunks = (
chunk: OutputChunk,
Expand Down Expand Up @@ -781,32 +781,61 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
chunk: OutputChunk,
toOutputPath: (filename: string) => string,
seen: Set<string> = new Set(),
parentImports?: Set<string>,
sapphi-red marked this conversation as resolved.
Show resolved Hide resolved
circle: Set<OutputChunk> = new Set(),
): HtmlTagDescriptor[] => {
const tags: HtmlTagDescriptor[] = []
if (circle.has(chunk)) {
return tags
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But there may be a problem here. If it is the previous logic, when encountering a module introduced in a loop, the css tag of the module will be generated first.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that is fine. Actually I think it's more a bug fix as it will align with this code:

const addDeps = (filename: string) => {
if (filename === ownerFilename) return
if (analyzed.has(filename)) return
analyzed.add(filename)
const chunk = bundle[filename]
if (chunk) {
deps.add(chunk.fileName)
if (chunk.type === 'chunk') {
chunk.imports.forEach(addDeps)
// Ensure that the css imported by current chunk is loaded after the dependencies.
// So the style of current chunk won't be overwritten unexpectedly.
chunk.viteMetadata!.importedCss.forEach((file) => {
deps.add(file)
})
}
} else {
const removedPureCssFiles =
removedPureCssFilesCache.get(config)!
const chunk = removedPureCssFiles.get(filename)
if (chunk) {
if (chunk.viteMetadata!.importedCss.size) {
chunk.viteMetadata!.importedCss.forEach((file) => {
deps.add(file)
})
hasRemovedPureCssChunk = true
}
s.update(expStart, expEnd, 'Promise.resolve({})')
}
}
}

}
circle.add(chunk)
let analyzedChunkImportCss: Set<string>
const processImportedCss = (files: Set<string>): void => {
files.forEach((file) => {
if (parentImports) {
parentImports.add(file)
}
if (!seen.has(file)) {
seen.add(file)
tags.push({
tag: 'link',
attrs: {
rel: 'stylesheet',
crossorigin: true,
href: toOutputPath(file),
},
})
}
})
}
if (!analyzedChunk.has(chunk)) {
analyzedChunk.set(chunk, 1)
analyzedChunkImportCss = new Set()
chunk.imports.forEach((file) => {
const importee = bundle[file]
if (importee?.type === 'chunk') {
tags.push(...getCssTagsForChunk(importee, toOutputPath, seen))
tags.push(
...getCssTagsForChunk(
importee,
toOutputPath,
seen,
analyzedChunkImportCss,
circle,
),
)
}
})
}

chunk.viteMetadata!.importedCss.forEach((file) => {
if (!seen.has(file)) {
seen.add(file)
tags.push({
tag: 'link',
attrs: {
rel: 'stylesheet',
crossorigin: true,
href: toOutputPath(file),
},
analyzedChunk.set(chunk, analyzedChunkImportCss)
if (parentImports) {
analyzedChunkImportCss.forEach((file) => {
parentImports.add(file)
})
}
})
} else {
analyzedChunkImportCss = analyzedChunk.get(chunk)!
processImportedCss(analyzedChunkImportCss)
}

processImportedCss(chunk.viteMetadata!.importedCss)
return tags
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think splitting the function into 3 like this will make the function more easier to understand

const toStyleSheetLinkTag = (
  file: string,
  toOutputPath: (filename: string) => string,
): 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 (analyzedChunk.has(chunk)) {
    return analyzedChunk.get(chunk)!
  }

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

  chunk.viteMetadata!.importedCss.forEach((file) => {
    if (!seenCss.has(file)) {
      seenCss.add(file)
      files.push(file)
    }
  })

  return files
}

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

I think analyzedChunk should be renamed to analyzedImportedCssFiles in this case.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think splitting the function into 3 like this will make the function more easier to understand

const toStyleSheetLinkTag = (
  file: string,
  toOutputPath: (filename: string) => string,
): 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 (analyzedChunk.has(chunk)) {
    return analyzedChunk.get(chunk)!
  }

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

  chunk.viteMetadata!.importedCss.forEach((file) => {
    if (!seenCss.has(file)) {
      seenCss.add(file)
      files.push(file)
    }
  })

  return files
}

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

I think analyzedChunk should be renamed to analyzedImportedCssFiles in this case.

Got it! But for the following situation, the current code still has a little problem

Comparison: entryA vs entryB (All import ChunkC, ChunkD)

entryA:

  • ChunkC(ChunkC import (ChunkD)):

    • seen: false
    • analized: false
    • generate: c.css, d.css
    • analizedCache: c.css, d.css
  • ChunkD:

    • seen: true
    • analized: true
    • generate: null
    • analizedCache: d.css
  • Final generated files: c.css, d.css


entryB:

ChunkB import (ChunkC):

  • ChunkC(ChunkC import (ChunkD)):

    • seen: false
    • analized: true
    • generate: c.css, d.css
    • analizedCache: c.css, d.css
  • ChunkD:

    • seen: false🤔
    • analized: true
    • generate: d.css❌
    • analizedCache: d.css
  • Final generated files: c.css, d.css, d.css

    • Note: d.css is repeated.

The following code is my improvement measure

        const seenFiles = new Set<string>();
        const addFile = (file: string) => {
          if (!seenFiles.has(file)) {
            seenFiles.add(file);
            files.push(file);
          }
        };

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

        chunk.viteMetadata!.importedCss.forEach((file) => {
          addFile(file)
        })


Expand Down
Loading