vitejs / vite-plugin-react

The all-in-one Vite plugin for React projects.
MIT License
544 stars 103 forks source link

Optimizing CSS File Size in Vite #342

Open harshitacodes opened 4 days ago

harshitacodes commented 4 days ago

I'm trying to understand how my index.css is being generated. I know that Vite uses esbuild to build the file chunks. However, I want to reduce the size of index.css by removing some unused CSS during the build process. The current size of index.css is quite large, causing it to block other elements from loading and significantly impacting page performance.

Any suggestions on how to achieve this?

Screenshot 2024-06-24 at 5 05 28 PM

Originally posted by @harshitacodes in https://github.com/vitejs/vite-plugin-react/discussions/341

Shakeskeyboarde commented 3 days ago

That is huge for a css file... is the original that big? If not, are you somehow embedding data urls (images) in it?

github-actions[bot] commented 3 days ago

Hello @harshitacodes. Please provide a minimal reproduction using a GitHub repository or StackBlitz. Issues marked with need reproduction will be closed if they have no activity within 3 days.

ArnaudBarre commented 3 days ago

I can't really help here, the simplest way to understand what in there is to open it, run prettier on it and see look for reference to libraries or assets and maybe see duplicated sections and then try to debug why this is unexpectedly bundled.

harshitacodes commented 3 days ago

That is huge for a css file... is the original that big? If not, are you somehow embedding data urls (images) in it?

Yes, I mean I am using images, but they are svgs. there are a lot of CSS modules being used in the project, but the issue is that Vite is somehow bundling similar files or CSS and putting them into these two files. I just want to know if there is any way to find out how Vite is creating this index.css file and what patterns it is using to generate it.

ArnaudBarre commented 2 days ago

If you load your JS into two big chunks, then Vite creates two big CSS chunks that where either imported by the JS files from the initial bundle or the second one. Codeplitting is always driven by JS imports

harshitacodes commented 4 hours ago

if Codeplitting is always driven by JS imports, then how can we load only critical css? , is there a anyway to confirgue that in the vite configuration file, or any pluggin?

ArnaudBarre commented 3 hours ago

You should always locate the CSS with the JS that needs it. Then you should use dynamic import to delay the use of non criticial JS