Profile
How to use PurgeCSS to reduce Tailwind CSS size in Laravel

Prerequisites

1. Basic knowledge about tailwind.css

2. Basic knowledge about Laravel

3. Install dependencies using `npm install @fullhuman/postcss-purgecss autoprefixer tailwindcss --save-dev` command

 

Let's do it!

First, you'll need to add tailwind function to your main CSS file, let's create one at resources/css/main.css like so

@tailwind base;

@tailwind components;

@tailwind utilities;

 

Then, add this code in webpack.mix.js

const mix = require('laravel-mix');

mix.postCss('resources/css/main.css', 'public/assets/css', [
    require('tailwindcss'),
    require('autoprefixer'),
    ...process.env.NODE_ENV === 'production' ? [
        require('@fullhuman/postcss-purgecss')({

            // Specify the paths to all of the template files in your project
            content: [
                './resources/views/**/*.blade.php',
            ],

            // Include any special characters you're using in this regular expression
            defaultExtractor: content => content.match(/[\w-/:]+(?<!:)/g) || []
        })
    ]: [],
]);

if (mix.inProduction()) {
    mix.version();
}

 

You can see that we will purge the CSS only if we build the file for the production environment. I have all my templates inside resources/views/ so I put it inside the content array above.

Now, let's run `npm run dev` and see how big the file is (see main.css file):

main.css file size before using PurgeCSS

The file takes up about 930 KB on my computer, that's not very big, but it's too big for my personal taste.

Now let's run `npm run prod` and see how big the file is (see main.css file):

You can see how crazy it is, the file size decreases from 930 KB down to only 7 KB (that's 132 times decrease in size). It will be even smaller when running through the network (because of gzipping compression). Let's see how small it is after gzipped:

 

 

The file size is about 2.5 KB after gzipped!

To summarize, it would be crazy not to use PurgeCSS if you use CSS in your project.