Skip to content

Commit 22545a6

Browse files
committed
feat: remove unused assets css in dist
When one imports an asset (let's say .svg) using import.meta.glob(..., { eager: true, import: 'default' }) new path will be inlined in a const and then this const get's tree-shaked/optimized, corresponding asset is not excluded from the final build. It's expected that no unused assets, especially heavy ones like fonts and images, are not included in final build. Fix: #19949 Ref: https://github.com/BerkliumBirb/vite-broken-tree-shaking
1 parent a679a64 commit 22545a6

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

packages/vite/src/node/plugins/asset.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
230230
generateBundle(_, bundle) {
231231
// Remove empty entry point file
232232
let importedFiles: Set<string> | undefined
233+
const importedCssAssets = new Set<string>()
233234
for (const file in bundle) {
234235
const chunk = bundle[file]
235236
if (
@@ -257,6 +258,24 @@ export function assetPlugin(config: ResolvedConfig): Plugin {
257258
delete bundle[file]
258259
}
259260
}
261+
if (chunk.type === 'chunk' && chunk.viteMetadata) {
262+
for (const importedAsset of chunk.viteMetadata.importedAssets) {
263+
importedCssAssets.add(importedAsset)
264+
}
265+
for (const importedCss of chunk.viteMetadata.importedCss) {
266+
importedCssAssets.add(importedCss)
267+
}
268+
}
269+
}
270+
271+
// Remove CSS and assets that were not imported by any chunk
272+
for (const file in bundle) {
273+
const chunk = bundle[file]
274+
if (chunk.type === 'asset' && importedCssAssets) {
275+
if (!importedCssAssets.has(cleanUrl(chunk.fileName))) {
276+
delete bundle[file]
277+
}
278+
}
260279
}
261280

262281
// do not emit assets for SSR build

0 commit comments

Comments
 (0)