How to Remove Unused CSS Classes from Tailwind CSS, Boostrap, and more with PurgeCSS

April 24, 2019

Track your progress

Sign in to track your progress and access subscription-only lessons.

Log In

Your Teacher

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

CSS frameworks like Tailwind, Bootstrap, Foundation, etc all come with many CSS classes you probably aren't using. This creates huge CSS files unless we use a tool like PurgeCSS to look through our code and remove the unused classes.

Notes

Resources

Code

yarn add @fullhuman/postcss-purgecss
// postcss.config.js

let environment = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
    require('postcss-import'),
    require('postcss-flexbugs-fixes'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009'
      },
      stage: 3
    }),
  ]
}

// Only run PurgeCSS in production (you can also add staging here)
if (process.env.RAILS_ENV === "production") {
  environment.plugins.push(
    require('@fullhuman/postcss-purgecss')({
      content: [
        './app/**/*.html.erb',
        './app/helpers/**/*.rb',
        './app/javascript/**/*.js',
        './app/javascript/**/*.vue',
        './app/javascript/**/*.jsx',
      ],
      defaultExtractor: content => content.match(/[A-Za-z0-9-_:/]+/g) || []
    })
  )
}

module.exports = environment

Want to stay up-to-date with Ruby on Rails?

Join 87,400+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.