Skip to content

Commit

Permalink
fix(css): ensure order of extracted CSS
Browse files Browse the repository at this point in the history
Without this the order of the extracted CSS rules is defined by the order `renderChunk` of the css plugin is called.
So with this the order of CSS rules is always in order of the output chunks of the bundle.

Signed-off-by: Ferdinand Thiessen <[email protected]>
  • Loading branch information
susnux committed May 30, 2024
1 parent 1f60647 commit 42319ec
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import postcssrc from 'postcss-load-config'
import type {
ExistingRawSourceMap,
ModuleFormat,
OutputAsset,
OutputChunk,
RenderedChunk,
RollupError,
Expand Down Expand Up @@ -843,23 +844,28 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
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]
function collect(chunk: OutputChunk | OutputAsset) {
if (!chunk || chunk.type !== 'chunk' || collected.has(chunk)) return
collected.add(chunk)

chunk.imports.forEach(collect)
chunk.imports.forEach((importName) => collect(bundle[importName]))
chunk.dynamicImports.forEach((importName) =>
collect(bundle[importName]),
)
css += chunkCSSMap.get(chunk.preliminaryFileName) ?? ''
}

for (const chunkName of chunkCSSMap.keys())
collect(prelimaryNameToChunkMap.get(chunkName)?.fileName ?? '')
// The bundle is guaranteed to be deterministic, if not then we have a bug in rollup.
// So we use it to ensure a deterministic order of styles
for (const chunk of Object.values(bundle)) {
if (
chunk.type === 'chunk' &&
(chunk.isEntry || chunk.isDynamicEntry)
) {
collect(chunk)
}
}

return css
}
Expand Down

0 comments on commit 42319ec

Please sign in to comment.