Have you ever run Chrome’s lighthouse on your site and seen an item called “unused css”? I have. And it’s annoying.
Deleting css by hand is prone to causing bugs. And, it’s a relatively stressful thing to do.
You’re looking at some css. And you’re pretty sure it’s not used.
…but what if it is.
Well, like most things in frontend dev these days, there is a
npm i solution for this problem.
This is fantastic for a number of reasons. For example, let’s say you’re using Tailwind.
You probably don’t use all those margin, padding, and/or even all those color classes. The same goes with Bootstrap. When’s the last time you’ve used one of everything they give you? Probably never.
PurgeCSS generally takes my css files and shrinks them at least by 50%.
My latest CRA project went from 90k => 40k.
The Bootstrap example below takes ALL of Bootstrap down to just 2kb.
Well, the problem is create-react-app doesn’t like letting you customize Webpack, Bable, eslint, and jest. They “take care” of it for you so you have a better modern js experience.
In this case, that won’t work.
We need to add some configuration to our webpack to get PurgeCSS working.
So, I solved this problem by using Create React App Configuration Override.
You’ll need to set this up first.
If some of your css is missing, you’ll want to read through the help docs on PurgeCss’s github repo to add whitelisted classes to your new webpack config.
If you need help setting up CRACO, you can find more documentation on their repo.