vitejs / vite

Next generation frontend tooling. It's fast!
http://vite.dev
MIT License
68.9k stars 6.23k forks source link

Svelte CSS treeshaking not working #15497

Open tomolenet opened 10 months ago

tomolenet commented 10 months ago

Describe the bug

We want to use the svelte kit library (building based on vite) configuration to build a component library that we integrate into a svelte kit app. When we import components as modules. For example like this:

import { Heading } from "svelte-kit-library";

Then we get in the build files all css stylings of other components that are not used or imported in the application. If the components are imported explicitly, there are no unwanted stylings in the build files.

import Heading from "svelte-kit-library/Heading.svelte";

Reproduction

https://github.com/tomolenet/svelte-kit-treeshaking

Steps to reproduce

In packages/svelte-kit-app we use the packages/svelte-kit-library in src/routes/+page.svelte. First use the module import in line 7.

import { Heading } from "svelte-kit-library";
# build app
npm run build -w packages/svelte-kit-app

Now check the output packages/svelte-kit-app/.svelte-kit. If you search for .unwanted which is styling of the Unwanted component of packages/svelte-kit-library you realize that styling exists in the build result. However, we have not imported the component at any point in the project.
Now change the import statement and use explicit import in line 10.

import Heading from "svelte-kit-library/Heading.svelte";
# build app
npm run build -w packages/svelte-kit-app

Now the .unwanted class is no longer included in the build. It seems that the tree shaking does not work correctly at this point.

System Info

System:
    OS: Linux 6.5 Manjaro Linux
    CPU: (8) x64 Intel(R) Core(TM) i7-8665U CPU @ 1.90GHz
    Memory: 5.50 GB / 15.29 GB
    Container: Yes
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.9.0 - ~/.nvm/versions/node/v20.9.0/bin/node
    npm: 10.1.0 - ~/.nvm/versions/node/v20.9.0/bin/npm
  Browsers:
    Chromium: 120.0.6099.129

Used Package Manager

npm

Logs

No response

Validations

bluwy commented 10 months ago

There was an attempt to fix this at https://github.com/sveltejs/vite-plugin-svelte/pull/760 but there's a Vite bug blocking marking CSS files as side-effect-less through moduleSideEffects. I'm not sure what the fix is, but perhaps we can use this issue to track fixing this.

tomolenet commented 10 months ago

Thank you for the introduction. We would be very grateful for a solution and I am willing to support if I can.