PostCSS partials using Gulp

I recently wrote a post about next gen CSS using Gulp about how you can write the latest CSS code and use Gulp to transpile it into more widely supported CSS using  cssnext.

Another neat feature that I like using is partial stylesheet files.  This is kind of like having separate stylesheets that you concatenate together to make one big stylesheet file, but in a more organised way that allows you to split one logical stylesheet into multiple logical chunks, making it easier for a team to work on a single stylesheet at once or just to help keep things modular and maintainable.

Before we get started, we need to install a plugin to make this work…

npm install --save-dev postcss-partial-import

And then we need to include the plugin, like this…

var partials = require("postcss-partial-import");

Now we can add this to the CSS task that we had in the previous post to give us something like this…

var css = function() {
  return gulp.src(cssFiles)
    .pipe(postcss([
      partials({prefix:"_",extension:".css"}),
      cssnext()
    ]))
    .pipe(gulp.dest("build/css"));
};

As you can see, we are passing a couple of options into the plugin:

  • prefix – this is the character that each file will start with, to indicate that it is a partial file (personally I like an underscore)
  • extension – you could use a different extension but I prefer to stick with “.css” so that the syntax highlighting works correctly in Atom (or your syntactically highlighted text editor of choice)

More options are available for the postcss-partial-import plugin, but this is all I find I generally need.

I like to put all of my variables (as we saw in the previous post) in a partial file called “_var.css”.  Now all I need to do is add the following into my main stylesheet file…

@import "var";

And all of those variables will be pulled into the top of this stylesheet when processed by Gulp.  As you can see, the require does not have the prefix, this is automatically included by the plugin when searching for the file.

Now I know exactly where to find my variables, because they’re in a separate partial file.

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.