Reduce CSS File Size With CSS Purge

In this tutorial we're going to learn how we can use a JavaScript library called Purge CSS to MASSIVELY reduce the sizes of CSS files. The way it will reduce the CSS file by searching for all the used classes and ID's in your source code and remove any CSS that isn' t used. For this tutorial I'm going to use Laravel mix to process the webpack building of the CSS file.

Install CSS Purge

To start with we need to install CSS purge and Glob.

npm install purgecss-webpack-plugin --save-dev
npm install glob-all --save-dev

Add CSS Purge Webpack Plugin To Mix

At the top of your Laravel webpack.mix.js file you need to include Purge CSS and Glob.

let purgeCss = require('purgecss-webpack-plugin')
let glob = require('glob-all')

Adding The Purge CSS Plugin During Production

We want the plugin to run just during our production process, therefore we can use the mix function inProduction to check the environment. Then we add the CSS Purge plugin to search in the resources folder for blade templates or Vue templates for what CSS classes or IDs are used.

mix.webpackConfig({
    plugins: [
        new purgeCss({
            paths: glob.sync([
                path.join(__dirname, 'resources/views/**/*.blade.php'),
                path.join(__dirname, 'resources/assets/js/**/*.vue')
            ]),
            extractors: [
                {
                    extractor: class {
                        static extract(content) {
                            return content.match(/[A-z0-9-:\/]+/g)
                        }
                    },
                    extensions: ['html', 'js', 'php', 'vue']
                }
            ]
        })
    ]
})

Full Webpack.mix File

let mix = require('laravel-mix');
let purgeCss = require('purgecss-webpack-plugin')
let glob = require('glob-all')
var tailwindcss = require('tailwindcss');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js');
mix.sass('resources/assets/sass/app.scss', 'public/css')
    .options({
        processCssUrls: false,
        postCss: [ require('postcss-import'), tailwindcss('tailwind.js') ],
    }).version();

if (mix.inProduction()) {
    mix.webpackConfig({
        plugins: [
            new purgeCss({
                paths: glob.sync([
                    path.join(__dirname, 'resources/views/**/*.blade.php'),
                    path.join(__dirname, 'resources/assets/js/**/*.vue')
                ]),
                extractors: [
                    {
                        extractor: class {
                            static extract(content) {
                                return content.match(/[A-z0-9-:\/]+/g)
                            }
                        },
                        extensions: ['html', 'js', 'php', 'vue']
                    }
                ]
            })
        ]
    })
}

Building Our Assets

When we run npm run dev webpack will now build our asset files in development mode which will not use CSS purge. This is the result of the build.

/js/app.js  1.65 MB
/css/app.css   246 kB

When we run npm run prod it will minify the JS and CSS files to get them as small as possible. This will already reduce the file size enough for a production environment. This command will reduce the file css to the following.


/js/app.js   186 kB
/css/app.css   179 kB

Now if we turn on purge CSS and re-run npm run prod we're now left with the following file sizes.


/js/app.js   186 kb
css/app.css   7.9 kB

As you can see the CSS file has gone from 179kb to 7.9kb, that's a HUGE 183% saving from an already compressed file, simply by searching for what CSS classes are actually used. ## Spatie PurgeCSS Package

Spatie have released a Laravel package that will add the above functionality into your application with zero config setup. All you have to do is include the package into your application and add the webpack function and that's it. Laravel Mix PurgeCSS First install it using npm.


npm install laravel-mix-purgecss

Then require it into your webpack config like below.


let mix = require('laravel-mix');
require('laravel-mix-purgecss');

// ...

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css')
   .purgeCss();

Ignoring CSS Classes

If you want to ignore certain classes from PurgeCSS you can whitelist them directly in the CSS file by wrapping them with comments.

/* purgecss start ignore */

.whitelist-this-class {
  background-color: red;
  color: yellow;
}

/* purgecss end ignore */

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring