Skip to content

Commit

Permalink
fix: unify css collecting order (#11671)
Browse files Browse the repository at this point in the history
  • Loading branch information
lsdsjy authored Sep 22, 2023
1 parent 1c2e941 commit 20a8a15
Showing 1 changed file with 28 additions and 9 deletions.
37 changes: 28 additions & 9 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import glob from 'fast-glob'
import postcssrc from 'postcss-load-config'
import type {
ExistingRawSourceMap,
NormalizedOutputOptions,
OutputChunk,
RenderedChunk,
RollupError,
Expand Down Expand Up @@ -376,8 +375,8 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {

// when there are multiple rollup outputs and extracting CSS, only emit once,
// since output formats have no effect on the generated CSS.
let outputToExtractedCSSMap: Map<NormalizedOutputOptions, string>
let hasEmitted = false
let chunkCSSMap: Map<string, string>

const rollupOptionsOutput = config.build.rollupOptions.output
const assetFileNames = (
Expand Down Expand Up @@ -407,8 +406,8 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
renderStart() {
// Ensure new caches for every build (i.e. rebuilding in watch mode)
pureCssChunks = new Set<RenderedChunk>()
outputToExtractedCSSMap = new Map<NormalizedOutputOptions, string>()
hasEmitted = false
chunkCSSMap = new Map()
emitTasks = []
},

Expand Down Expand Up @@ -700,10 +699,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
chunkCSS = resolveAssetUrlsInCss(chunkCSS, cssBundleName)
// finalizeCss is called for the aggregated chunk in generateBundle

outputToExtractedCSSMap.set(
opts,
(outputToExtractedCSSMap.get(opts) || '') + chunkCSS,
)
chunkCSSMap.set(chunk.fileName, chunkCSS)
}
return null
},
Expand Down Expand Up @@ -785,8 +781,31 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
})
}

let extractedCss = outputToExtractedCSSMap.get(opts)
if (extractedCss && !hasEmitted) {
function extractCss() {
let css = ''
const collected = new Set<OutputChunk>()
const prelimaryNameToChunkMap = new Map(
Object.values(bundle)
.filter((chunk): chunk is OutputChunk => chunk.type === 'chunk')
.map((chunk) => [chunk.preliminaryFileName, chunk]),
)

function collect(fileName: string) {
const chunk = bundle[fileName]
if (!chunk || chunk.type !== 'chunk' || collected.has(chunk)) return
collected.add(chunk)

chunk.imports.forEach(collect)
css += chunkCSSMap.get(chunk.preliminaryFileName) ?? ''
}

for (const chunkName of chunkCSSMap.keys())
collect(prelimaryNameToChunkMap.get(chunkName)?.fileName ?? '')

return css
}
let extractedCss = !hasEmitted && extractCss()
if (extractedCss) {
hasEmitted = true
extractedCss = await finalizeCss(extractedCss, true, config)
this.emitFile({
Expand Down

0 comments on commit 20a8a15

Please sign in to comment.