Next gen CSS using Gulp

I really hate the phrase “next gen”, it’s heavily overused and usually means that something derivative has been created, rather than something innovative.  But in this case, I am referring to some of the newer features of CSS3 which aren’t supported by all browsers yet, and how Gulp can allow you to use them now, by transpiling to more widely supported CSS.

This isn’t something that has made it into one of my Gulp workflow courses (1 and 2) yet, but perhaps it will in future.  It’s not really about improving the efficiency or performance of your website, but has lots to do with improving your development of CSS.

The tool that we’ll be using is called cssnext, and in their words…

You can literally write future-proof CSS and forget old preprocessor specific syntax

One of the main things that we’re going to look at in this example is using CSS variables, but the feature list is quite impressive.  It’s likely to replace pre-processors like LESS and SASS in the future, or certainly reduce their benefit.

To get started, we need to install the plugins that we’re going to need for this, like this…

npm install --save-dev gulp-postcss postcss-cssnext

Let’s break those down:

  • gulp-postcss – this is used to pipe CSS through several plugins, but parse CSS only once, which improves performance
  • postcss-cssnext – this is a PostCSS plugin that provides the cssnext functionality that we’re after

Now that we have those two both install, we need to include them in our Gulpfile.js…

var postcss = require("gulp-postcss");
var cssnext = require("postcss-cssnext");

Now the way that we use it is actually very simple – your CSS task (in Gulp 4) could look something like this…

var css = function() {
  return gulp.src(cssFiles)
    .pipe(postcss([cssnext()]))
    .pipe(gulp.dest("build/css"));
};

We’re simply picking up our files (using a variable in this case) and piping them through PostCSS, including cssnext as one of the plugins to use.  PostCSS can take any number of plugins in this array and will pass the CSS files through all of them in turn.

And it really is as simple as that.  Now you can write CSS like this…

:root {
  --primary-color: blue;
}

h1 {
  color: var(--primary-color);
}

And you’ll get output like this…

h1 {
  color: blue;
}

Just what you need to safely write some “next gen” CSS.

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.