From 023be7b6b3df21ae20e5da3b239dd6fe4581b151 Mon Sep 17 00:00:00 2001 From: lsdsjy Date: Wed, 9 Aug 2023 17:37:02 +0800 Subject: [PATCH] refactor: collect CSS in `generateBundle` --- packages/vite/src/node/plugins/css.ts | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 2b8d40b2bb20bd..8941270ea13de7 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -6,7 +6,6 @@ import glob from 'fast-glob' import postcssrc from 'postcss-load-config' import type { ExistingRawSourceMap, - NormalizedOutputOptions, OutputChunk, RenderedChunk, RollupError, @@ -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 let hasEmitted = false + let chunkCSSMap: Map const rollupOptionsOutput = config.build.rollupOptions.output const assetFileNames = ( @@ -409,7 +408,6 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { buildStart() { // Ensure new caches for every build (i.e. rebuilding in watch mode) pureCssChunks = new Set() - outputToExtractedCSSMap = new Map() hasEmitted = false emitTasks = [] }, @@ -708,10 +706,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 }, @@ -792,7 +787,23 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { }) } - let extractedCss = outputToExtractedCSSMap.get(opts) + function extractCss() { + let css = '' + const collected = new Set() + 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)