diff options
author | 2023-10-04 21:18:39 +0800 | |
---|---|---|
committer | 2023-10-04 21:18:39 +0800 | |
commit | aa265d73024422967c1b1c68ad268c419c6c798f (patch) | |
tree | 90c3382137c4eb0bd0a7c40d4aa477f0b3f60ff0 | |
parent | b18d4bf3b17cf98cf5bbc488772773bdfcc38ec4 (diff) | |
download | astro-aa265d73024422967c1b1c68ad268c419c6c798f.tar.gz astro-aa265d73024422967c1b1c68ad268c419c6c798f.tar.zst astro-aa265d73024422967c1b1c68ad268c419c6c798f.zip |
Remove unused CSS output files when inlined (#8743)
-rw-r--r-- | .changeset/tasty-meals-buy.md | 5 | ||||
-rw-r--r-- | packages/astro/src/core/build/plugins/plugin-css.ts | 22 |
2 files changed, 25 insertions, 2 deletions
diff --git a/.changeset/tasty-meals-buy.md b/.changeset/tasty-meals-buy.md new file mode 100644 index 000000000..1df456b68 --- /dev/null +++ b/.changeset/tasty-meals-buy.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Remove unused CSS output files when inlined diff --git a/packages/astro/src/core/build/plugins/plugin-css.ts b/packages/astro/src/core/build/plugins/plugin-css.ts index d85dc8e56..85652e13b 100644 --- a/packages/astro/src/core/build/plugins/plugin-css.ts +++ b/packages/astro/src/core/build/plugins/plugin-css.ts @@ -200,7 +200,7 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] { const inlineConfig = settings.config.build.inlineStylesheets; const { assetsInlineLimit = 4096 } = settings.config.vite?.build ?? {}; - Object.entries(bundle).forEach(([_, stylesheet]) => { + Object.entries(bundle).forEach(([id, stylesheet]) => { if ( stylesheet.type !== 'asset' || stylesheet.name?.endsWith('.css') !== true || @@ -224,10 +224,15 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] { : { type: 'external', src: stylesheet.fileName }; const pages = Array.from(eachPageData(internals)); + let sheetAddedToPage = false; pages.forEach((pageData) => { const orderingInfo = pagesToCss[pageData.moduleSpecifier]?.[stylesheet.fileName]; - if (orderingInfo !== undefined) return pageData.styles.push({ ...orderingInfo, sheet }); + if (orderingInfo !== undefined) { + pageData.styles.push({ ...orderingInfo, sheet }); + sheetAddedToPage = true; + return; + } const propagatedPaths = pagesToPropagatedCss[pageData.moduleSpecifier]; if (propagatedPaths === undefined) return; @@ -243,8 +248,21 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] { pageData.propagatedStyles.set(pageInfoId, new Set()).get(pageInfoId)!; propagatedStyles.add(sheet); + sheetAddedToPage = true; }); }); + + if (toBeInlined && sheetAddedToPage) { + // CSS is already added to all used pages, we can delete it from the bundle + // and make sure no chunks reference it via `importedCss` (for Vite preloading) + // to avoid duplicate CSS. + delete bundle[id]; + for (const chunk of Object.values(bundle)) { + if (chunk.type === 'chunk') { + chunk.viteMetadata?.importedCss?.delete(id); + } + } + } }); }, }; |