Nov 04. 2018 · by Helge Sverre

How to use PurgeCSS with Laravel Mix in a Craft CMS Project.

PurgeCSS is a a package that you can use to strip out unused CSS from your stylesheet, greatly reducing the file size when using a framework like Bootstrap, Tailwind CSS or Foundation.

I recently used this on a website project where I was using Bootstrap (properly), and saw great reduction in filesize, making the page load faster.

Here is how I did it using Laravel Mix, first you need to add the NPM package.

Add the npm package
yarn add laravel-mix-purgecss

# Or 

npm install laravel-mix-purgecss --save-dev

Then we have to configure it to look for our twig template files (to figure out which css classes are used), and any javascript or Vue components you might be using (I always put my Javascript in a src/ folder in the root of my project)

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


    .js('src/js/app.js', 'public/dist/app.js')
    .sass('src/sass/app.scss', 'public/dist/app.css')
        enabled: mix.inProduction(),
        folders: ['src', 'templates'],
        extensions: ['twig', 'html', 'js', 'php', 'vue'],

And you're ready to go!

Run npm run production or yarn production to compile your code and strip out unused CSS.

Happy coding.