How to reduce tailwindcss file size using purgecss

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.

--

--

--

Growth at Moni(YC W22) | Adebola.dev

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Using the URLSearchParams Object in JavaScript — Part 1

Create a Percentage Calculator with Vue 3 and JavaScript

Agora Web UIKit: Add Video Calling or Live Streaming to Your Website in Minutes

vj for your home; a postmortem

Framework-free, no-build websites: how far can they take you in 2021?

Getting Started with UI Development with Chakra UI Vue

A React hook to share state between browser windows

React Native — Status Bar and Image Styles

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
Adebola Adeniran

Adebola Adeniran

Growth at Moni(YC W22) | Adebola.dev

More from Medium

React Admin: Introduction

YesStyle Clone

How to dynamically change the background image of a website in Vue/React

A Walkthrough for fetching API