@@ -7,6 +7,7 @@ import postcssrc from 'postcss-load-config'
7
7
import type {
8
8
ExistingRawSourceMap ,
9
9
ModuleFormat ,
10
+ OutputAsset ,
10
11
OutputChunk ,
11
12
RenderedChunk ,
12
13
RollupError ,
@@ -844,23 +845,34 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
844
845
function extractCss ( ) {
845
846
let css = ''
846
847
const collected = new Set < OutputChunk > ( )
847
- const prelimaryNameToChunkMap = new Map (
848
- Object . values ( bundle )
849
- . filter ( ( chunk ) : chunk is OutputChunk => chunk . type === 'chunk' )
850
- . map ( ( chunk ) => [ chunk . preliminaryFileName , chunk ] ) ,
851
- )
848
+ // will be populated in order they are used by entry points
849
+ const dynamicImports = new Set < string > ( )
852
850
853
- function collect ( fileName : string ) {
854
- const chunk = bundle [ fileName ]
851
+ function collect ( chunk : OutputChunk | OutputAsset ) {
855
852
if ( ! chunk || chunk . type !== 'chunk' || collected . has ( chunk ) ) return
856
853
collected . add ( chunk )
857
854
858
- chunk . imports . forEach ( collect )
855
+ // First collect all styles from the synchronous imports (lowest priority)
856
+ chunk . imports . forEach ( ( importName ) => collect ( bundle [ importName ] ) )
857
+ // Save dynamic imports in deterministic order to add the styles later (to have the highest priority)
858
+ chunk . dynamicImports . forEach ( ( importName ) =>
859
+ dynamicImports . add ( importName ) ,
860
+ )
861
+ // Then collect the styles of the current chunk (might overwrite some styles from previous imports)
859
862
css += chunkCSSMap . get ( chunk . preliminaryFileName ) ?? ''
860
863
}
861
864
862
- for ( const chunkName of chunkCSSMap . keys ( ) )
863
- collect ( prelimaryNameToChunkMap . get ( chunkName ) ?. fileName ?? '' )
865
+ // The bundle is guaranteed to be deterministic, if not then we have a bug in rollup.
866
+ // So we use it to ensure a deterministic order of styles
867
+ for ( const chunk of Object . values ( bundle ) ) {
868
+ if ( chunk . type === 'chunk' && chunk . isEntry ) {
869
+ collect ( chunk )
870
+ }
871
+ }
872
+ // Now collect the dynamic chunks, this is done last to have the styles overwrite the previous ones
873
+ for ( const chunkName of dynamicImports ) {
874
+ collect ( bundle [ chunkName ] )
875
+ }
864
876
865
877
return css
866
878
}
0 commit comments