Improving the accuracy of PurgeCSS
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?
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:
- PurgeCSS works by scanning source files such as HTML, CSS, JS, etc.
- 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
- render such components in ways that ensure those fleeting styles show up.
- take snapshots and store them in files
- Point PurgeCSS to consider those files when scanning for used styles
Jest snapshots look like:
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.