withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
46.8k stars 2.49k forks source link

Barrel file import stops tree-shaking for css in production build #11545

Closed RogierdeRuijter closed 3 months ago

RogierdeRuijter commented 3 months ago

Astro Info

Astro                    v4.11.6
Node                     v20.12.0
System                   macOS (arm64)
Package Manager          npm
Output                   static
Adapter                  none
Integrations             @astrojs/lit

If this issue only occurs in one browser, which browser is a problem?

any

Describe the Bug

When using a barrel file to import an Astro component, tree-shaking does not happen for the css in a production build. As stated here: https://github.com/withastro/astro/issues/701#issuecomment-882986173, this is undesired behaviour, if that comment is still valid.

The following screenshot shows that MyAstroComponent and MyAstroComponent1 css is both loaded onto the page even though only 1 component is present.

image

How to reproduce

Note

On the 'no-barrel' branch the version without barrel imports can be seen

What's the expected result?

Only inject the css of the components that are on the page

Link to Minimal Reproducible Example

https://github.com/RogierdeRuijter/astro-barrel

Participation

bluwy commented 3 months ago

I think this problem is specific to code-splitting and not treeshaking. It should treeshake correctly if you only import one of the components only for example, and only that CSS will be bundled.

Unfortunately wrt code-splitting, it's a known bug at the moment and not something we can fix. The gist of the issue is explained at https://github.com/vitejs/vite/pull/16058#issuecomment-1972860379. How Vite handles CSS may need to be reworked/refactored if we want to fix this.

Since this will require changes from Vite, I'll close this in favour of an upstream solution for now.