in Laravel

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.

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.

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.

Full Webpack.mix File

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();

Login to access all content on Paulund

Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email