Removing duplicate styles in Gulp

Almost two years ago, I first talked about adding stylesheets into my Gulp file, as part of the development workflow that I was working on at the time (and still am).  Over that time, I’ve experimented further and wanted to update you on the settings I use these days.

Back then I was using Gulp 3, so let’s give an updated sample task in Gulp 4…

var css = function() {
  return gulp.src(["css/*.css"])
    .pipe(sourcemaps.init())
    .pipe(concat("style.css"))
    .pipe(cleancss())
    .pipe(sourcemaps.write("../maps"))
    .pipe(gulp.dest("build/css"));
};

As you can see I’m adding sourcemaps in this example, as well as concatenating as I did in the original snippet.

However, instead of calling cleancss() with no parameters, I now like to pass in some options, like this…

    .pipe(cleancss({level:{1:{specialComments:0},2:{removeDuplicateRules:true}}}))

So what’s going on here?  Well firstly, as I described in my earlier post, the clean-css plugin has two optimisation levels…

  1. These operate on single properties only, and are mostly on by default.
  2. These operate on multiple properties at a time, including restructuring and reordering rules, but are off by default.

So we actually pass in the options for the two different levels at the same time, but I only tend to set one option per level:

  • specialComments (level 1) – special comments are ones that start with /*! which tells minification tools not to remove these comments – these are typically used for the attribution, version, licence, etc. but Google Insights and other speed test tools often flag that the file could be further compressed if these are included, so I now like to force them to be removed by setting this to 0
  • removeDuplicateRules (level 2) – this is particularly handy if you are including more than one library that have similar reset rules – in the example I gave recently when purifying stylesheets, Bootstrap and FontAwesome both include the “sr-only” class for screenreader only text – you don’t need both so you can remove one by setting this to true

There are a many more optimisations that you can make by enabling more level 2 options especially, but I find these two options give me good results.

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.