Setting Up PurgeCSS Without Ejecting From Create React App

Posted on July 10, 2019

Why Purge CSS

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.

Meet PurgeCSS!

Essentially, PurgeCSS reads through your javascript and html to see what classes you’ve used in your files. They then remove all css from your files that is not invoked by these classes.

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.

The Problem

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.

Here’s How To Setup PurgeCSS With CRA

  1. Setup CRACO: Setup
  2. npm i —save-dev path glob-all purgecss-webpack-plugin
  3. Alter Your craco.config.js file to look like the file below.

Go To Gist


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.