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.
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');
require('laravel-mix-purgecss');
mix
.js('src/js/app.js', 'public/dist/app.js')
.sass('src/sass/app.scss', 'public/dist/app.css')
.purgeCss({
enabled: mix.inProduction(),
folders: ['src', 'templates'],
extensions: ['twig', 'html', 'js', 'php', 'vue'],
})
.setPublicPath('public');
And you're ready to go!
Run npm run production
or yarn production
to compile your code and strip out unused CSS.
Happy coding.
Host your CraftCMS websites with a secure, affordable and easy to manage VPS provider.
Get $10 free credits on signup