Tuesday, April 26, 2016

Improving the Quality of Your CSS with PostCSS

The term "code quality" is not new to programmers. After all, every developer knows that it's not enough for the code to just work. It should also possess other qualities: it should be readable, well formatted and consistent. It should also match a certain standard of quantitative metrics. Unfortunately, this is often overlooked when writing CSS. We can spend a lot of time debating why this happens, but the important part is that CSS is code as much as JavaScript, PHP or anything else, and we should pay attention to the way we write it. Otherwise, it may cause things to be more complicated than they should be.

In this article, we will explore how we can utilise PostCSS to help us maintain a higher quality in our CSS code. First, let's try to pinpoint what we actually mean by "better CSS code". There are several things to watch out for:

  • Code should be consistent in style - You are free to choose how you name your classes, where you place new lines or how you list the properties, but you should do it in the same manner across all of your stylesheets. Consistent style improves readability and makes the code easier to understand.
  • Code should respect some metric standards - There are quantitative metrics that we can measure and keep at a certain threshold, such as the maximum precision of any selector or number of unique colours used on a page.
  • Hacks should be avoided - Certain constructs, such as, the !important directive may seem like a feasible solution at times, but they usually just make the code more complex.

Certainly this is not a complete list, but let's focus on the above problems for now. They might seem obvious, but they can be easily overlooked when working on a large project with a big team where people can vary in skill. What we would like is a tool that can help us enforce these standards automatically by means of code analysis. This is where PostCSS comes in.

How Can PostCSS Help

In the previous article about PostCSS here at SitePoint, we covered what PostCSS is and how its plugins can be used for various purposes. In this article, we will focus on several PostCSS plugins that can help us keep our CSS code quality at its best.

Before we start, let's set up a sandbox project we can experiment on. As opposed to using PostCSS via the command line as in the previous article, we'll use Gulp instead. Start by creating a new folder and initiating an npm project there. After that we'll need to install Gulp, the PostCSS plugin, and a reporter plugin for viewing the output of PostCSS plugins. To do that, navigate to the newly created project and run:

[code language="bash"]
npm i gulp gulp-postcss postcss-reporter --save-dev
[/code]

After that create an empty style.css file and a gulpfile.js with the following contents:

[code language="js"]
var gulp = require('gulp');
gulp.task('analyze-css', function () {
var postcss = require('gulp-postcss');
var reporter = require('postcss-reporter');

return gulp.src('style.css')
.pipe(postcss([
reporter()
]));
});
[/code]

This will define a task that will scan the contents of style.css and run it through a series of PostCSS plugins. You can already run gulp analyze-css but it won't do much since there's only a reporting plugin with nothing to report. Let's add our first linting plugin.

Stylelint

By now there is surely a linter for any language and CSS is no exception. Stylelint allows you to validate your CSS code against a predefined set of rules which can check your code for consistent formatting, usage of certain rules, units or directives, as well as potential mistakes (such as incorrect colors). It allows you to define over a hundred rules — some of them do basic stuff, for instance, ensuring there is a space between a selector and the following curly brace, or that only single quotes are used. Others are more interesting. Here are a few examples:

  • property-blacklist and unit-blacklist allow you to specify a list of properties and units that cannot be used.
  • property-no-vendor-prefix warns you about using vendor prefixes for properties that don't require them based on data from Can I use.
  • declaration-no-important disallows using the !important directive.
  • selector-max-specificity limits the maximum specificity of a selector.

Stylelint ships with all of the rules disabled by default, so you are expected to configure the rules yourselves. This can take a while, considering the amount of rules it has. Alternatively, you can use a predefined config such as stylelint-config-standard and extend it with your own rules.

Let's set up stylelint with a standard rule set:

[code language="bash"]
npm i stylelint stylelint-config-standard --save-dev
[/code]

You'll also need to extend your gulpfile to enable the new plugin:

[code language="js"]
var gulp = require('gulp');
gulp.task('analyze-css', function () {
var postcss = require('gulp-postcss');
var stylelint = require('stylelint');
var reporter = require('postcss-reporter');

return gulp.src('style.css')
.pipe(postcss([
stylelint(),
reporter()
]));
});
[/code]

Stylelint rules can be configured inline in the gulpfile, but I prefer to keep them in a separate file. Create a .stylelintrc file in your project folder and add the following contents:

[code language="js"]
{
"extends": "stylelint-config-standard"
}
[/code]

This will tell stylelint that our own rule set will be based on the standard config. Now let's update our style.css file and test the plugin against this savage piece of CSS:

[code language="css"]
.title,.content{
background: #FFFFFF;
font-size:0.9em;

margin: 0;
}
[/code]

Continue reading %Improving the Quality of Your CSS with PostCSS%


by Pavels Jelisejevs via SitePoint

No comments:

Post a Comment