Improving the accuracy of PurgeCSS

Handling styles that only show up at runtime

Ikechi Michael
2 min readApr 28, 2022

Like many, I use PurgeCSS to remove unused CSS in my frontend apps. It does the job by scanning through source files such as HTML, Pug, JSX and even CSS, to find styles the application uses, then it filters a target CSS file to only have styles that are used.

This approach works great unless there are used styles that cannot be found by scanning the source files. A good example is styles that are applied at runtime by libraries. PurgeCSS will not know about such styles, and this can lead to badly rendered UI from missing styles.

How can we let PurgeCSS know about styles that only show up at runtime, and cannot be found by scanning the available source code?

Safelisting

A technique I’ve seen is populating the safelist object in PurgeCSS’ config.

While this is an option, I do not particularly like this technique because it requires that I maintain a list of these runtime styles, and I have to remember to remove these styles from the safelist when they no longer need to be there.

Feeding PurgeCSS with more accurate data

So we know a few things:

  1. PurgeCSS works by scanning source files such as HTML, CSS, JS, etc.
  2. We have a problem with styles that show up at runtime

What if we could save a snapshot of components that render these fleeting styles, and feed that to PurgeCSS to look at?

So using tools like Jest and Enzyme, we

  1. render such components in ways that ensure those fleeting styles show up.
  2. take snapshots and store them in files
  3. Point PurgeCSS to consider those files when scanning for used styles

Jest snapshots look like:

This means every Jest snapshot is a valid JavaScript file of exported strings and this is good, cos we can write a script to save every exported string into a file that PurgeCSS can “learn” from.

I prefer this approach because it lets me “kill two birds with one stone”. I can keep my components properly tested, and ensure PurgeCSS has enough context to purge styles properly.

--

--

Ikechi Michael

I’ve learned I don’t know anything. I've also learned that people will pay for what I know. Maybe that's why they never pay.