@@ -200,7 +200,7 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] {
200200 const inlineConfig = settings . config . build . inlineStylesheets ;
201201 const { assetsInlineLimit = 4096 } = settings . config . vite ?. build ?? { } ;
202202
203- Object . entries ( bundle ) . forEach ( ( [ _ , stylesheet ] ) => {
203+ Object . entries ( bundle ) . forEach ( ( [ id , stylesheet ] ) => {
204204 if (
205205 stylesheet . type !== 'asset' ||
206206 stylesheet . name ?. endsWith ( '.css' ) !== true ||
@@ -224,10 +224,15 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] {
224224 : { type : 'external' , src : stylesheet . fileName } ;
225225
226226 const pages = Array . from ( eachPageData ( internals ) ) ;
227+ let sheetAddedToPage = false ;
227228
228229 pages . forEach ( ( pageData ) => {
229230 const orderingInfo = pagesToCss [ pageData . moduleSpecifier ] ?. [ stylesheet . fileName ] ;
230- if ( orderingInfo !== undefined ) return pageData . styles . push ( { ...orderingInfo , sheet } ) ;
231+ if ( orderingInfo !== undefined ) {
232+ pageData . styles . push ( { ...orderingInfo , sheet } ) ;
233+ sheetAddedToPage = true ;
234+ return ;
235+ }
231236
232237 const propagatedPaths = pagesToPropagatedCss [ pageData . moduleSpecifier ] ;
233238 if ( propagatedPaths === undefined ) return ;
@@ -243,8 +248,21 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] {
243248 pageData . propagatedStyles . set ( pageInfoId , new Set ( ) ) . get ( pageInfoId ) ! ;
244249
245250 propagatedStyles . add ( sheet ) ;
251+ sheetAddedToPage = true ;
246252 } ) ;
247253 } ) ;
254+
255+ if ( toBeInlined && sheetAddedToPage ) {
256+ // CSS is already added to all used pages, we can delete it from the bundle
257+ // and make sure no chunks reference it via `importedCss` (for Vite preloading)
258+ // to avoid duplicate CSS.
259+ delete bundle [ id ] ;
260+ for ( const chunk of Object . values ( bundle ) ) {
261+ if ( chunk . type === 'chunk' ) {
262+ chunk . viteMetadata ?. importedCss ?. delete ( id ) ;
263+ }
264+ }
265+ }
248266 } ) ;
249267 } ,
250268 } ;
0 commit comments