Tuesday, June 14, 2016

7 PostCSS Plugins to Ease You into PostCSS

We've featured PostCSS many times before on SitePoint, yet it continues to confuse many. To summarize it in one sentence:

PostCSS handles tedious jobs so you don't have to.

It is subtly different to a pre-processor such as Sass, Less and Stylus which provide an alternative, more concise programming language which compiles to CSS. Part of the confusion is caused by:

  • Its name. PostCSS can perform actions on files either before and/or after a pre-processor has compiled its source code to real CSS.

  • PostCSS could replace your pre-processor. There are plugins which implement constructs such as variables, nesting, mixins and extends.

However, while you can build your own pre-processor, there's little reason to do so unless you want to limit the functionality and increase compilation speed. Personally, I use Sass followed by a sprinkling of PostCSS seasoning to enhance my CSS.

How Do You Use PostCSS?

PostCSS can be used within standalone JavaScript files, Gulp, Grunt, Broccoli, Brunch and a wide range of task runners I've never heard of!

On its own, PostCSS does nothing but parse a CSS file into JavaScript objects and tokens. The real magic happens with plugins which examine, manipulate, add or change properties and values before the final CSS file is written.

To use PostCSS in Gulp, you need to set-up your project then install both modules:

[code language="bash"]
npm init
npm install --save-dev gulp gulp-postcss
[/code]

You can then add the plugins you require, e.g. autoprefixer and cssnano:

[code language="bash"]
npm install --save-dev autoprefixer cssnano
[/code]

A gulpfile.js can be created. It defines a task which loads the CSS source and pipes it through PostCSS. Plugins and any required options are passed to PostCSS in an array. Finally, the CSS is output to a destination file:

[code language="js"]
// Gulp.js configuration
var gulp = require('gulp'),
postcss = require('gulp-postcss');

// apply PostCSS plugins
gulp.task('css', function() {
return gulp.src('src/main.css')
.pipe(postcss([
require('autoprefixer')({}),
require('cssnano')
]))
.pipe(gulp.dest('dest/main.css'));
});
[/code]

The task can be run from the console with:

[code language="bash"]
gulp css
[/code]

All we need now is a handy list of PostCSS plugins...

Continue reading %7 PostCSS Plugins to Ease You into PostCSS%


by Craig Buckler via SitePoint

No comments:

Post a Comment