Mastering PostCSS for Web Design
上QQ阅读APP看书,第一时间看更新

Setting the order of plugins

At this point, there is a key part of PostCSS we need to cover: the order we use when calling plugins in our task runner file. This might seem a little odd, but there are two good reasons for considering this when developing with PostCSS:

  • The first reason is simple—it's about making sure that we maintain a logical order of when tasks are completed at compilation.
  • The second is a little more obscure, and will come with experience—some plugins need to be defined in the task file in a certain order, for them to work correctly.

Let's explore what this means:

If we take a look at the gulp task file that we've slowly been building up, you will notice a key difference between lines 13 and 19; and no, it's not the task name, before you ask! The difference is the ['lint-styles'] constraint—this forces Gulp not to run this task until its predecessor has completed:

I know this might sound like common sense, and that I am only preaching what you may already know, but getting the order that plugins are called in PostCSS is critical to the successful compilation of your file.

As an example, when researching for this book, I frequently found that either my source map was only being produced for an uncompressed version of my style sheet, or that the minified style sheet wasn't being created at the right point. Simple issues, but tweaking the order can have a serious impact on what happens and when!

Continuing with the theme of order, it is likely you may see notes akin to this when browsing the source site of a PostCSS plugin:

This underlines why getting the order of your plugins is essential for an effective result: not only will tasks be completed in the right order and produce the expected results, but some plugins won't even work. This should not necessarily be taken as being a fault; there will be a valid reason that means plugin X must come before plugin Y. The key thing here is that we take any constraints into consideration. It is worth checking, as others may add patch support to remove constraints, or fix it through forking their own version of the plugin.

Okay, time to change focus and take a look at some different functionality: mixins. For the uninitiated, this is a key function frequently used in preprocessors such as SASS, where we can mix-in (yes, pun intended!) blocks of code.

The idea here being that we can create anything, from a simple few lines to a complex, dynamic code excerpt that PostCSS will compile into our code and use to produce valid CSS. Let's dive in and take a closer look.