A key part of any website is styling—it doesn't matter if this is for a simple element tag or a complex animation; a website is not a website without color and action. Building styles for any online presence takes time and effort—we can reduce development time by using a preprocessor to automate the creation of styles, automatically apply vendor prefixes and the like, but the extra dependency of a library can be like using a sledgehammer to crack a nut!
Enter PostCSS—its unique modular style allows us to create a leaner, faster CSS processor, with no external dependencies. In this chapter, we look at installing PostCSS, understanding its architecture, and learn how to use its speed and power to compile code into valid CSS. We will cover a number of topics throughout this chapter, which will include the following:
Considering the benefits of creating our own preprocessor
Introducing PostCSS and exploring its features
Setting up a development environment using PostCSS
Creating a simple example using PostCSS
Exploring how PostCSS works and its architecture
Let's make a start…!
A question: what do SASS, Stylus, Haml, and Less all have in common?
The answer is, they are all compilers, source to source compiling, or transpilers (to give them their official name), that have been around since the 1980s. They have appeared in many different formats, with Digital Research's XLT86 being one of the earliest versions, dating from 1981.
More recently, the well-known SASS processor arrived in 2006; this was followed by Less, created by Alexis Sellier in 2009. Both work in a similar fashion: they take a set of rules and compile it into valid CSS. We can extend CSS with all manner of features, such as variables, mixins, functions, and more. Although processors may not help cut down the physical number of lines we have to write, they help us reorganize code into more manageable blocks that we can reuse in future projects, which helps make CSS easier to maintain.
But, as is nearly always the case, there are some drawbacks to using processors:
There is nearly always a dependency involved, in some form or other—with SASS, it's Ruby; if you're using Less, it's a library, even though it is written in JavaScript
Our project may only use a small amount of preprocessed code, yet we are forced to rely on what can be a large library, such as SASS
Processing style sheets using a preprocessor is slow; it may only be a few seconds, but this builds up over time to become a significant amount of time spent waiting for processes to complete
Hmm, this doesn't make processing so attractive! But what if there were a way to alleviate all of these issues, and remove the need for dependencies at the same time?
Well, there is: let's build our own processor! Okay, this might sound a little crazy, but as someone once said, there is method in this madness, so bear with me while I explain why this may be a better option.
At the beginning of this chapter, I mentioned that we would focus on creating our own preprocessor, right? Well, I have a little confession to make: we're not. Hold on, what gives?
Well, we will create a preprocessor…but we will also create a postprocessor too. Let me explain why—our alternative "option" allows us to create both at the same time. Our alternative option is PostCSS, which can be downloaded from https://github.com/postcss/postcss. PostCSS is used by some major companies, such as Twitter, Google, Bootstrap and CodePen, and even WordPress (in a limited capacity).
PostCSS was built as a Node.js module, so will work with any number of the existing plugins already available for Node.js—we will be using a number of these plugins throughout the book. Let's take a moment to explore some of the benefits of this tool.
What do we mean by PostCSS? In a nutshell, it can be used to refer to one of two things—the PostCSS core tool or the plugin ecosystem that is powered by the tool. On its own, it doesn't actually do a lot; once we start adding plugins, we can achieve a great deal. Let's explore what this means in practice:
Its modular architecture means we can pick and choose what we use; this allows us to keep the size of the library very small and responsive.
Existing processors tend to fall into one of two camps—pre- or post-processing—which is a limiting factor when choosing which to use. PostCSS allows us to perform both operations within the same process, meaning we get the benefits of both worlds of processing!
PostCSS comes with seamless support for all of the common task runners such as Gulp, Grunt, or Broccoli; we can combine it with a number of other tasks that can be automated.
There are no dependencies for compiling, PostCSS is written entirely in JavaScript, so no need for Ruby, or libraries such as
libsass
, in order to compile code. The only dependency (as such) is Node.js—many developers will likely already have this installed.There is no need to learn any new languages; every developer will be familiar with JavaScript, and use it in their development process.
We can change any plugin in use for something else when needed; we do not get this choice when using a larger library.
Its relatively low barrier of entry means we can create any plugins we need very easily, or potentially modify existing ones to better suit our needs.
PostCSS is quick—in a test using the
postcss-benchmark
plugin (available from https://github.com/postcss/benchmark), which contained parsed code, nested rules, mixins, variables, and math, PostCSS came out a clear winner:Perfect—no need to continually update SASS, or have to download a new version of the
libsass
library, right?
Well, there are some considerations to using a custom processor; the key thing to remember is that PostCSS is neither a pre- nor post-processor, but more of a Swiss Army Knife of a toolbox that we can use to process our CSS code. Let's take a look at some of these drawbacks:
Although we don't need to learn a new language in order to use PostCSS, creating a custom processor will add a layer of complexity to our development process.
Its flexible approach means some may treat PostCSS as either a preprocessor or a postprocessor; this short-sighted approach means that you will miss opportunities, so it is crucial to keep an open mind in terms of what PostCSS can offer your development process.
Converting code from an existing preprocessor to using PostCSS can be painful; this process only works if we don't try to convert explicitly, but use it as a basis for progressively moving to using PostCSS.
PostCSS requires syntactically correct CSS from the start; although we could use any syntax (as PostCSS files are just plain text), compilation can easily fail, even through use of a single line comment!
The real benefit of using PostCSS, though, is in its seamless integration into tools such as Gulp—imagine this scenario if you will:
You already develop sites using a preprocessor such as SASS. You can compile code using a standalone processor, but normally prefer to use Node.js and Gulp to complete the task. Sound about right? What about making the move to using PostCSS?
No problem, we can include a section for processing CSS files using PostCSS. The key here is to not use PostCSS to perform the initial compilation, but to perform the post-processing, such as adding vendor prefixes or minifying the results. Once this is established, we can start to incorporate some of the plugins available for PostCSS that allow us to replicate functionality, such as from within SASS. Once we've adjusted existing code to use the format required by the plugins, we can then switch to using PostCSS, and begin to remove our dependency on using SASS.
At this point, it is worth spending a few minutes to help clear up some common misconceptions about PostCSS, although many associate it as being a preprocessor, or even a postprocessor, this isn't what was intended:
Classing PostCSS as a postprocessor, as opposed to a preprocessor (such as Less or SASS) is misguided; PostCSS is capable of compiling in a variety of different use-case scenarios, working on code compiled using any preprocessor, or just plain CSS.
PostCSS should not be classed as a tool that should be tied in to any one process (such as writing SASS-based loops or conditionals). There are plugins available to do both, but this is just a small part of the role that PostCSS can play in your development workflow.
If you find yourself in a position where "PostCSS" doesn't appear to perform as expected, it is unlikely to be PostCSS itself, but more likely to be a plugin being used that is causing the issue. Although PostCSS is still relatively young, there are plenty of plugins available, so it is worth trying alternatives if you can as a first port of call.
Okay, let's move on, I think it's time for less chat and more action, right? Let's get stuck in to producing something; there's no better time than now to get PostCSS installed and ready for use.
Before we do so, we just need to cover a couple of requirements. First, we need to set up a local web server. It's not critical, but gives a better effect. I personally use WAMP Server (for PC, from http://www.wampserver.com/en), otherwise, Mac users can try MAMP (http://www.mamp.info/en), or the cross-platform Apache web server (from http://www.apachefriends.org). In each case, default settings should be sufficient.
The second requirement is to set up a project area; assuming you have set up a WAMP as a local web server, go ahead and set up a folder called postcss
in c:\wamp\www
, as shown in this screenshot:
Right, with that out of the way, let's make a start on getting PostCSS installed!
The first step on our journey is to get PostCSS installed—this runs from Node.js; we can use any one of several task runner plugins to install it. For the purpose of the exercises throughout this book, we will use Gulp; if you prefer, alternatives such as Grunt or Broccoli can be used.
Note
When using Node.js, make sure you use the Node.js command prompt, and not node.exe
; the exercises will not work when using the latter!
Let's make a start with installing Node and Gulp:
We first need to install Node.js; this is available at http://nodejs.org. Make sure you select the right version that is appropriate for your platform:
When installing, accept all defaults; this will be sufficient for the exercises throughout this book.
Next, bring up a Node.js command prompt, enter the following command, and press Enter:
node –v
The output shown is the version of Node that is installed; this is a quick check to ensure Node.js has indeed been installed correctly:
Now that Node is installed, we need to create a
package.json
file to store our dependencies for projects. Run this command at the command prompt, and press Enter:npm init
Node will prompt for information when creating the
package.json
file; enter the details as shown in the screenshot, or press Enter to accept the given default (shown in brackets, after each question):
We now have Node configured and an empty package.json
file in place, so let's add our dependencies. We will start by adding Gulp first:
Revert back to the Node.js command prompt (or bring up a new one if you closed off the previous session).
Go ahead and change the working directory to
c:\wamp\www\postcss
.At the command prompt, enter the following command, then press Enter. This installs Gulp globally and makes it available for use:
npm install --global gulp
Once done, we need to install Gulp for use in our project area—go ahead and run this command, which will add an entry to the
package.json
file we created earlier in step 3 and step 4:npm install --save-dev gulp
Once completed, Gulp is now ready for use; we can go ahead and install PostCSS.
Note
A small point on the use of --save-dev
: this installs any dependencies required to develop using a specific plugin; if we simply need the dependencies for running the plugin (in a production environment), then we can simply use --save
instead.
We're at the interesting stage now—installing PostCSS. PostCSS is available from https://github.com/postcss/postcss, and can be installed into Node using a Gulp plugin. Let's do that now:
We'll start by reverting back to the Node.js command prompt session we've just used (or a new one, if the previous one is closed).
At the prompt, go ahead and enter this command, then press Enter:
npm install --save-dev gulp-postcss
If all is well, we should see something akin to this screenshot:
On its own, PostCSS doesn't do anything; to make it more useful, we are going to install three plugins. We will explore using plugins in greater detail later in the book, but for now, don't worry too much about what is happening:
Enter these commands one by one on the Node.js command prompt, pressing Enter after each one:
npm install --save-dev autoprefixer
Let's check our
package.json
file; if all is well, we should see something akin to this screenshot:Tip
To make it easier to view JSON files in Sublime Text, try installing and activating a custom theme, such as MonokaiJSON Plus, available to install from https://github.com/ColibriApps/MonokaiJsonPlus.
PostCSS is now installed for use, but if we try to use it, we probably won't get very far, as it needs to be configured for use! Let's take a look at doing that now, by creating a simple example that will add vendor prefixes to some sample CSS rules, and automatically minify the results.
PostCSS is a fascinating tool; its modular architecture leaves it wide open to being used in a variety of different use-case scenarios, or even a mix of several! Throughout this book, we'll touch on different uses, before bringing them all together to create a processor that can both pre- and post-process files within the same workflow.
To give you a taste of how well it works, we're going to build a simple processor now; this will automatically add vendor prefixes and spit out minified versions during compilation.
Let's make a start, we've installed the relevant plugins, so let's go create our Gulp task file:
In a new file, add the following code, saving it as
gulpfile.js
at the root of our project area:In the project area, create a folder called
dest
; other folders will be created, but these will be done automatically during compilation.In a new file, add the following code, saving it as
example.css
in thesrc
folder of our project area:body { display: flex; background: green; }
Revert back to the Node.js command prompt, then at the command prompt, enter the following command and press Enter:
gulp styles
Within a matter of seconds (almost instantaneously), we should see a compiled
example.css
appear in thedest
folder of our project area.We can prove PostCSS has done its job properly; go ahead and open up
example.css
in a text editor: if all is well, we should see this:
Perfect, we now have a working PostCSS installation; any time we need to add vendor prefixes, we can just fire up our compilation process, and away we go…
Or do we? Ah, there is much more to PostCSS than simply adding vendor prefixes! Remember how I mentioned that PostCSS is often (incorrectly) labelled as a pre- or post-processor?
Well, there is much more we can do; one of the key benefits of PostCSS is being selective about how we process our code. We're not forced to rely on dependencies (such as Ruby for SASS); we can instead produce something that is very light and quick. In our previous example, we created a task called styles
; we'll change this to use the task name default
, which will allow us to run multiple tasks from one command. This means we can simply call gulp
, instead of needing to supply the task name.
Let's put this to the test and start to expand on our compilation process by adding source map support—we'll use the source map plugin for Gulp by Florian Reiterer, available from https://github.com/floridoo/gulp-sourcemaps:
We'll start, as always, by installing the plugin using Node—fire up a Node.js command prompt, then change to our project area.
Next, enter this at the command line and press Enter:
npm install --save-dev gulp-sourcemaps
Open up the
gulp
file we created back in the Creating a simple example using PostCSS section, then add a reference togulp-sourcemaps
as a variable:var autoprefixer = require('autoprefixer'); var sourcemaps = require('gulp-sourcemaps');
We then need to add the commands to create the source maps—in the same file, alter the code as shown:
.pipe(postcss([ autoprefixer ])) .pipe(sourcemaps.init()) .pipe(sourcemaps.write('maps/')) .pipe(gulp.dest('dest/'));
Save the results, then from the Node.js command prompt, run this command, and press Enter:
gulp styles
If all is well, we should see a new source map appear in the
dest
folder, under a subfolder calledmaps
.We're a step further in the right direction; we now have a map file for our style sheet in the maps folder, created automatically during the compilation process.
Note
It's worth noting that we will make full use of this area—if you see any reference to
project area
throughout the book, this will be our given name for this folder.But, we can do more: although we only have a small CSS file here, it's still important to compress it to save on unnecessary bandwidth usage. We can easily fix that using PostCSS—let's take a look at how, using the
cssnano
plugin.
A key part of producing style sheets is minifying the output; this should feature as standard in any developer's workflow. Minifying the results will cut down on bandwidth usage. In an age of broadband or cable use, this is less critical for smaller sites, but should not attract any less importance than for larger sites!
Thankfully, minifying files is a cinch to achieve when working with PostCSS. For this next exercise, we will use the
cssnano
and gulp-rename
plugins, available from http://cssnano.co/ and https://github.com/hparra/gulp-rename, respectively. Let's go ahead and get them installed:
We'll start by firing up a Node.js command prompt, then entering the following and pressing Enter:
npm install -–save-dev cssnano npm install -–save-dev gulp-rename
Don't close the session window, we will use it later in this exercise.
Switch to the
gulpfile.js
file we created earlier (it's stored at the root of our project folder), then add the following lines immediately after the last closing})
on or around line 12:gulp.task('rename', ['styles'], function () { return gulp.src('dest/example.css') .pipe(postcss([ cssnano ])) .pipe(rename('example.min.css')) .pipe(gulp.dest("dest/")); }); gulp.task('default', ['styles', 'rename']);
At the top of the file, we need to add two declarations, otherwise our code will fail; go ahead and add the following two lines, as highlighted:
var sourcemaps = require('gulp-sourcemaps'); var rename = require('gulp-rename'); var cssnano = require('cssnano');
Any sharp-eyed readers may now spot a problem—in the last line, we have a reference to
styles
, yet nothing is shown in the code for this! To fix it, we need to change our code. In line 8, change the line as shown:gulp.task('styles', function() {
Save the file, then switch back to the Node.js command prompt window and enter this command, followed by Enter:
gulp
Gulp will now compile:
If all is well, we should see the compiled output appear in the
dest
folder of our project area:
In our project area, we not only have the source map file created under maps, but now also have a minified style sheet, the latter created by renaming the output from cssnano
(cssnano
does not do this renaming natively, hence use of the rename
plugin).
Unfortunately though, we still have one small issue—take a look at the contents of the maps
folder: notice anything? Hopefully, you may spot that the source map file is there for the uncompressed version of our style sheet, but not the compressed one! Let's fix that now. To do so, we just need to use the rename
task in our Gulp file, as shown:
.pipe(rename('example.min.css')) .pipe(sourcemaps.init()) .pipe(sourcemaps.write('maps/')) .pipe(gulp.dest("dest/"));
Try running Gulp now. If all is well we should see the source map appear for our minified style sheet:
Let's finish off our gulp
file; the last stage is to add a watch
facility, so that changes are compiled automatically as soon as files are modified.
Adding a
watch
facility is simple when using Gulp. It helps reduce the manual effort required when using Gulp, as we only need to fire off the Gulp task file once, and it will continue to apply the tasks each time files are changed.
Unlike other plugins, we don't need to install any plugins for this; simply add the highlighted lines from the following to the gulpfile.js
file:
gulp.task('default', ['styles', 'rename', 'sourcemaps']); var watcher = gulp.watch('src/*.css', ['default']); watcher.on('change', function(event) { console.log('File ' + event.path + ' was ' + event.type + ', running tasks...'); });
We can see the results of the addition to our gulp task file, and how it all comes together, in this screenshot:
At this point, we can save the file then re-run the gulp
command as before; this time it will automatically recompile any file that has changed, from within the src
folder. In this instance, we've added an event handler to log an indication into the session so we can tell what is happening; we can easily modify this if needed.
We now have a basic working system; we will begin to add to this over the next few chapters, toward building up our own processor. There is one small thing we should cover though: it's not essential, but a useful tip for developing with PostCSS. I'm talking about linting your code, to ensure it is valid; let's dive in and get this set up for use.
It goes without saying that linting code should be part of any developer's workflow. There are lots of different ways to achieve this, depending on the tools you use. The beauty of PostCSS is that we can easily add a suitable linting capability to our processor, using the stylelint
plugin for PostCSS (available from http://stylelint.io/).
Why would we do this? Easy: we can get a single consistent result throughout. This becomes essential if you work as part of a team; instead as different team members using inconsistent settings, we can set up a central point for processing, to retain a consistent output. Moving the linting process to our central workflow means the server can do the grunt work for us, and provide a consistent result anytime for anyone running the process.
With this in mind, let's take a look at how we can set up our linting capability:
We start as always by installing our plugin. For this, fire up a Node.js command prompt, then change to the root of our project area.
At the command prompt, enter this command, followed by Enter:
npm install stylelint
If all is well, we should see this appear at the prompt:
Next up, we need to install a second plugin—there is a reporter function within
stylelint
that posts any messages to console (or in this case, screen). The plugin ispostcss-reporter
, and is available at https://github.com/postcss/postcss-reporter. We can install it thus:With the plugins installed, we need to update our
gulp
file; add the following lines immediately below the lastvar
line shown:var cssnano = require('cssnano'); var stylelint = require('stylelint'); var reporter = require('postcss-reporter');
Immediately, below the rename task in the Gulp file, add this task—this takes care of linting our code, and flagging any errors on-screen:
gulp.task("lint-styles", function() { return gulp.src("src/*.css") .pipe(postcss([ stylelint({ "rules": { "color-no-invalid-hex": 2, "declaration-colon-space-before": [2, "never"], "indentation": [2, 2], "number-leading-zero": [2, "always"] } }), reporter({ clearMessages: true, }) ])) });
Open a copy of
example.css
from the root area of our project folder and change thecolor
to#fff1az
.Back in the Node.js command prompt, enter this command and press Enter:
gulp
Gulp will begin to process our code; if all is well, it should flag a warning:
It shouldn't take much effort to spot that #fff1az
is clearly not a valid number! Stylelint has correctly identified it, using the highlighted rule from our configuration:
.pipe(postcss([ stylelint({
"rules": {
"color-no-invalid-hex": true,
…
}
}),
Let's explore how this plugin works for a moment—the great thing about it is that there are simply dozens of rules available (which you can see at https://cdn.rawgit.com/stylelint/stylelint/1.0.0/docs/rules.md). It works by concatenating together what is being checked (in this case, color
) and the check being run against it (in our case, -no-invalid-hex, or checking for invalid hex numbers). We can apply any number of rules in our configuration object, to ensure that the output is consistent for all projects.
Tip
If you would like to get a feel for how the rules can be put together, then check out the user guide at https://cdn.rawgit.com/stylelint/stylelint/1.0.0/docs/user-guide.md, with more examples of rules available at https://cdn.rawgit.com/stylelint/stylelint/1.0.0/docs/rules.md.
Okay, let's move on: we will begin to look at compiling code in more detail from the next chapter, but for now, let's take a look at how PostCSS works in more detail, and how we can begin to make the move from our existing processor to PostCSS.
So far, we've covered the basics of setting up and using PostCSS. It's worth taking a moment to learn about how it works, to better understand how we can use it and develop our own plugins for the platform.
PostCSS is like me on a Saturday morning after a good night out: it does nothing! Yes, it's true, by itself, the application doesn't do anything at all; it's when we add plugins into the mix that it starts to become useful.
The key to PostCSS is treating it as an enabler, it is not meant as a direct replacement for your existing preprocessor, or even postprocessor, but to complement them. It works on the basis of parsing code, processing it with any assigned plugins, and rendering the results:
It works by parsing content into an Abstract Syntax Tree (or AST) with a series of nodes. Each node in the tree contains a symbolic representation of an element in your code. In other words, if you had a condition statement that pointed to three possible outcomes, then the AST would have a single node, with three branches representing the possible outcomes.
Note
For an example of an AST, take a look at http://jointjs.com/demos/javascript-ast, which shows the breakdown of a simple arithmetic function using plain JavaScript.
Our AST is then sent through one or more plugins (we must always use one plugin, but can have many in our gulp
file). It then converts the code to a long string, before processing it through any assigned plugins and spitting out the result in the form of valid CSS. We can use this as a basis for creating our own plugins, using the boilerplate code and API that are both available from the main PostCSS site on GitHub.
The trick to the plugin stage is in the mix of plugins we must use to satisfy our needs; the better ones should only perform one role. Any that perform multiple tasks are less ideal, as they are likely to contain excess functionality that we don't need in our projects.
Assuming we decided to use PostCSS, there is almost always one question at the top of everyone's mind: how do we make the move?
In short, the key here is not to simply assume existing code can be put through the PostCSS process, as it will likely not work. Instead, we should take an iterative process, and begin to convert low-hanging fruit to using PostCSS. The process will of course require some work, but there are tips on how we can reduce the pain involved in making the switch to PostCSS.
The key to making the transfer is to work out what functionality needs to be processed, then to create the initial framework for a build process (for example, a Gulp or Grunt task file), then to gradually add in plugin support one by one, until you have a fully working compiler.
We can take this a step further, and use plugins that replicate SASS code format into PostCSS; an ideal plugin to start with is Autoprefixer, followed by plugins such as postcss-mixins
or postcss-partial-import
. We will explore using SASS as a basis for a custom syntax in Chapter 11, Manipulating Custom Syntaxes, where we will use these two plugins, and more, to help make the transition process easier and help remove the dependencies on preprocessors such as SASS or Less. Oh, and above all, being based on JavaScript makes it portable; what more could a developer ask for, I wonder?
Note
Many of the SASS format plugins for PostCSS now come in the PreCSS
pack. We will explore using this in Chapter 10, Building a Custom Preprocessor.
Okay, on we go. Over the course of the next few chapters, we will take a look at different processor elements that are commonly used to create build processors, such as variables or mixins. We'll see how they might typically be written in processors such as SASS or Less, then work on converting our code to use PostCSS equivalents before processing to produce valid CSS. We will then finish up with pulling everything together to build your own custom processor for use in future projects.
Writing valid CSS is an art that has been present since the dawn of the Internet; this takes skill, patience, and time to produce and perfect any masterpiece. Processors such as SASS or Less have helped to make the process more efficient, but are not without their drawbacks; PostCSS allows for a more customized approach, but without the extra baggage. We've covered a few key points around PostCSS throughout this chapter, so let's take a moment to review what we've learned.
We began with a brief look at the art of processing, before introducing PostCSS as a tool. We then explored some of the benefits and drawbacks of using it, and how it can fit in seamlessly with your existing development workflow, with a little careful planning.
Next up, we covered the installation of PostCSS along with Gulp as the task runner/host process, before embarking on a simple demo to introduce how the compilation process works, and that with the right choice of plugins, we can take out some of the manual grunt work required to manage our code (pun intended!). With our code compiling, we then turned our attention to adding a watch facility, and automatic support for linting our code, to ensure we maintain consistent standards.
We then rounded out the chapter with a look at how PostCSS works, and understanding something of its architecture, so that we can begin to make the move from using plain CSS or an existing preprocessor, to using PostCSS.
Phew, we've certainly covered a lot; it's time to really get stuck in now, and start to use PostCSS in earnest. Over the next few chapters, we will explore a number of different concepts that are common to existing preprocessors, and explore how we can benefit from making the transition to using PostCSS. We have to start somewhere, so we'll kick off with using variables, functions, and mixins in the next chapter, and see how we can use some of the techniques from processors, but without the associated baggage!