Removing Unused CSS in Tailwind with PurgeCSS

Share this video with your friends

Send Tweet

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.

alex rodriguez
~ 6 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
~ 6 years ago

Great course, Simon! Thanks for putting it together.

Simon Vrachliotisinstructor
~ 6 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
~ 6 years ago

Excellent! Worked perfectly. Thanks again, Simon!