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

Introducing variables and mixins

So far, we've covered the basics of installing and configuring PostCSS—although there are a few steps involved, it's an easy process to get started with using the processor. To really get to know it though, there is no substitute for using it in anger; it's amazing how much you can automate, with just a little care and planning!

Let's put that to the test and use it to create a couple of simple examples using variables, functions, and mixins. We'll start with creating the original version using SASS, before converting it to use PostCSS plugins. The demos do assume a level of prior knowledge around using SASS, so if you are at all unfamiliar, then you may like to refer to my book, SASS Essentials, available from Packt Publishing.

Note

A word of note: we will make good use of the project folders we created back in Chapter 1, Introducing PostCSS, where src will be our in-tray, and dest will contain the compiled code. Make sure you have this open in a window somewhere on your desktop!

Okay, the first step in this process is to get SASS installed, so let's take a look at that now.

Setting up SASS

Setting up SASS is really easy when using Gulp; we can use the same format of command to install it as we do for other plugins. The source code for the plugin is available at in turn is a Node binding for the C+ library, libsass.

Let's dive in and take a look at getting it installed:

  1. We start, as usual, with Node. Fire up a Node.js command prompt session, then change to the working directory.
  2. At the command prompt, enter the following, then press Enter:
    npm install --save-dev gulp-sass
    
  3. If all is well, we should see something akin to this screenshot:

Before we continue, though, I would recommend clearing out or saving the contents of the dest folder elsewhere for safe keeping, after each exercise:

  1. Next up, open a copy of gulpfile.js in Sublime Text; we need to make a number of changes, beginning with adding a reference to the gulp-sass plugin (as highlighted):
    var reporter = require('postcss-reporter');
    var sass = require('gulp-sass');

    SASS will, by default, produce code in unminified format; the addition of {outputStyle: 'compressed'} in the task will automatically compress the output code. This makes this line redundant, so go ahead and remove it:

    var cssnano = require('cssnano');
  2. We also need to remove the reference to cssnano on or around line 19, so go ahead and remove this line:
    .pipe(postcss([ cssnano ]))
  3. On or around line 10, change the name of the styles task to autoprefixer and the dependency name to lint-styles:
    gulp.task('autoprefixer', ['lint-styles'], function() {
    return gulp.src('src/*.css')

    Then remove these two lines:

    .pipe(sourcemaps.init())
    .pipe(sourcemaps.write('maps/'))
  4. In the rename task, modify the rename task to match this:
    gulp.task('rename', ['lint-styles'], function () {
      return gulp.src('dest/*.css')
        .pipe(rename('style.min.css'))
        .pipe(sourcemaps.init())
        .pipe(sourcemaps.write('maps/'))
        .pipe(gulp.dest("dest/"));
    });
  5. On or around line 25, we need to add in the lint-styles task—go ahead and add in this block of code, which will check our styles for consistency:
    gulp.task("lint-styles", ['sass'], 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,
        })
      ]))
    });
  6. We're almost done. Add in the next task; this tells Gulp about how we should compile any SASS files presented to the task runner:
    gulp.task('sass', function () {
      gulp.src('src/*.scss')
        .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
        .pipe(gulp.dest('src/'));
    });
  7. We need to make a couple more changes. The key task that fires off a call to each of the sub tasks needs to be updated, to reflect the changes to our tasks:
    gulp.task('default', ['sass', 'lint-styles', 'autoprefixer', 'rename']);
  8. Our last change is to alter the watch facility to check for SASS files, and not pure CSS; go ahead and change the configuration object as shown:
    var watcher = gulp.watch('src/*.scss', ['default']);

At this point, we have set up our processor to compile SASS files to valid CSS. We can prove this by compiling any SASS file. If all is well, our processor will produce valid style sheets and accompanying source map files automatically. Let's put this to the test as part of our next exercise, where we create an intriguing hover effect for images.