Skip to content

Commit

Permalink
refactor: collect CSS in generateBundle
Browse files Browse the repository at this point in the history
  • Loading branch information
lsdsjy committed Aug 9, 2023
1 parent 490dad8 commit 763b52a
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 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 @@ -378,8 +377,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 @@ -409,8 +408,8 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
buildStart() {
// 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 @@ -708,10 +707,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 @@ -792,7 +788,23 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
})
}

let extractedCss = outputToExtractedCSSMap.get(opts)
function extractCss() {
let css = ''
const collected = new Set<string>()
function collect(chunkName: string) {
if (collected.has(chunkName)) return
collected.add(chunkName)

const chunk = bundle[chunkName]
if (chunk.type !== 'chunk') return

chunk.imports.forEach(collect)
css += chunkCSSMap.get(chunk.preliminaryFileName) ?? ''
}
for (const chunkName of chunkCSSMap.keys()) collect(chunkName)
return css
}
let extractedCss = extractCss()
if (extractedCss && !hasEmitted) {
hasEmitted = true
extractedCss = await finalizeCss(extractedCss, true, config)
Expand Down

0 comments on commit 763b52a

Please sign in to comment.