How to reduce tailwindcss file size using purgecss

Image for post
Image for post

Tailwindcss compiles to quite a large file size. In production, we do not need all the classes tailwind offers us and we would love to strip those classes out when our Application is in production.

This guide will show you how to use purgecss to strip out unused tailwind classes in production.

If you have never used tailwindcss, here’s how to set it up with Create-react-app.

Let’s start!

  1. Once you’ve followed all the configurations above, install purgecss using
yarn add @fullhuman/postcss-purgecss

2. Update your package.json. This allows the app know when it’s in production or development by adding the line below. We will be changing the build script.

{
"build": "NODE_ENV=production npm run build:css && react-scripts build"
}

3. Once updated, next step is to update our postcss.config file. Copy and paste the code below. It should replace the current code in your postcss.config.js file.

const devEnv = {
plugins: [require("tailwindcss"), require("autoprefixer")],
};

NB: Pay special attention to the content line. Make sure it matches the paths in your file that use the tailwind classes.

One way to check if our purgecss is working correctly, is by inspecting your application in production using chrome dev tools. Change one of the tailwind classes anywhere in your code to use a class that you haven’t declared. You should see that it doesn’t work correctly.

Enjoy! Make sure to leave a clap if this helped you.

Written by

Full-stack Engineer. Rails/Node.js/React. I love plantain chips! Reach me at Adebola.dev.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store