Removing Unused CSS in Tailwind with PurgeCSS

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

When you create new utilities, variants, breakpoints in Tailwind, the file size of your generated CSS bundle can become quite large. Adding PurgeCSS as a build step makes this worry go away and shrinks your CSS down by removing any class that is never used.

Man 1: [00:00] Here is a simple out-of-the-box set of utility classes generated with the default tailwind config. If we open up the devtools, you can see that the Compass css is 272 kilobyte heavy. Unminified and [indecipherable] , that is.

[00:15] As you add custom utility classes, colors, breakpoints and state variance, your bundle size will become larger and larger. Fear not, though. With a simple, extra step in your build workflow, you can make all the extra unused bloat go away.

[00:29] Let's install gulp purgecss quickly. We can now require it in our gulp file -- const purgecss = require('gulp-purgecss'). Right after running our css through tailwind, we'll pipe that into purgecss. We need to pass a content value which is, in our case, any html file in our distpath.

[00:51] All right, let's try to run gulp again and see what happens. Let's hard refresh the page and...Wow! 7.5 kilobytes. That was well worth the effort. If we look at our compile styles now, we only have the class name using the html page, background purple, font sense margin bottom -- 1. Let's comment out that purgecss step for a second, and rerun gulp. Refresh the page, and yep, we're back to 272.

alex rodriguez
alex rodriguez
~ 5 years ago

Thanks this was great! One small issue I am encountering, though... purgecss removes css with prefixes from the final file. Any thoughts how to get around that? Thanks again!

Fabricio
Fabricio
~ 5 years ago

Great course, Simon! Thanks for putting it together.

Simon Vrachliotis
Simon Vrachliotisinstructor
~ 5 years ago

Thanks this was great! One small issue I am encountering, though... purgecss removes css with prefixes from the final file. Any thoughts how to get around that? Thanks again!

Turns out that to avoid the : prefixed classes to be stripped, you need to pass a custom extractor to purgeCSS:

/* 
Custom extractor for purgeCSS to avoid 
stripping classes with `:` prefixes
*/
class TailwindExtractor {
  static extract(content) {
    return content.match(/[A-z0-9-:\/]+/g) || [];
  }
}

and then, in the CSS gulp task:

  .pipe(
    purgecss({
      content: [paths.dist.base + "*.html"],
      extractors: [
        {
          extractor: TailwindExtractor,
          extensions: ["html", "js"]
        }
      ]
    })

Let me know if that helps!

alex rodriguez
alex rodriguez
~ 5 years ago

Excellent! Worked perfectly. Thanks again, Simon!