How to reduce tailwindcss file size using purgecss

Adebola Adeniran
2 min readJul 27, 2020

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")],
};
if (process.env.NODE_ENV === "production") {
devEnv.plugins.push(
require("@fullhuman/postcss-purgecss")({
content: ["./src/components/**.jsx", "./src/components/**.js"],
defaultExtractor: (content) => content.match(/[A-Za-z0-9-_:/]+/g) || [],
})
);
}
module.exports = devEnv;

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.

--

--

Adebola Adeniran

Chief of Staff at Moni (YC W22) | Developer Advocate Building on Tezos