Purifying your stylesheets using Gulp

Sounds interesting, right? I bet you didn’t even know your stylesheets were dirty. Well they can be.

There are many really useful things that you can get from a CSS framework, such as Bootstrap, or a CSS icon set, such as FontAwesome.  You get loads of functionality out of the box that you can quickly include and use in your project without having to reinvent the wheel.  But this comes at a cost.  Not a financial cost, but a performance cost when asking your users to download these not insignificant files when you may only be using a small portion of them.  The minified Bootstrap file and the minified FontAwesome file are 153kb each, so if you’re using both then that’s 306kb.  Not huge, but we don’t need all that bloat, right?

It’s estimated that on average only 40% of the selectors in any given framework/library are actually used in a website or web application.  If we could get rid of the 60% that we’re not using we could save 184kb in the above example.  And I’ve created projects that use a lot less than 40% before!

The first thing that we need to do is install the gulp-purifycss plugin using NPM…

npm install --save-dev gulp-purifycss

This in turn uses the purify-css package (with a hypen, there is one without but it’s been deprecated), which is where most of the magic happens.

Before we get onto that though, we need to require it at the top of your “gulpfile.js” file (if you’re not automatically requiring plugins)…

var purifycss = require("gulp-purifycss");

Then it can be called to purify our stylesheet and remove that bloat…

var css = function() {
  return gulp.src(["css/*.css"])
    .pipe(concat("style.css"))
    .pipe(purifycss(["*.htm"]))
    .pipe(gulp.dest("build/css"));
};

As you can see, we start by concatenating all of the stylesheets in our project.  This should include local copies of the Bootstrap and FontAwesome files (or whatever other frameworks/libraries that you’re using).  It’s important that they are local, so that we can strip out the bloat.

We also need to pass into the plugin call an array of the files which will be calling the styles, which is most likely to be HTML and javascript, so that they can be scanned for class names to be kept.

So that’s it, your final out stylesheet file will now include all of the bits of Bootstrap and FontAwesome that your project is calling, but none of the bits that it’s not, significantly reducing the overall filesize.

And if you’re thinking it would be better just to use a CDN to load the full framework/library files, please read about why you should always self host static assets and then come back and purify those stylesheets.

This is covered in detail in the second of my Optimising your website courses on Skillshare/Udemy.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.