Minify CSS Files Using gulp-cssnano

 ·  · 

There's an article about how to minify CSS files by gulp-minify-css already.

But the gulp-minify-css package has been deprecated in favor of gulp-cssnano. Here are quick notes and snippets about using gulp-cssnano.

 

1 Installation

$ npm install gulp-cssnano --save-dev

Configurations in gulp.js:

/* gulpfile.js */

var gulp = require('gulp');
var cssnano = require('gulp-cssnano');

// bool flag to check whether current env is development or not
// true:        development
// false:       production
var isDebug = ((process.env.NODE_ENV || 'development').trim().toLowerCase() !== 'production');

var source = 'src/';    // project source code folder
var dest = 'dist/';     // project  distribution folder

var css = {
    in: source + 'css/*.css',
    out: dest + 'css/'
};

 

2 Gulp Task

Add minifying task for CSS files.

/* gulpfile.js */
.......

gulp.task('css', function () {
    var cssfile = gulp.src(css.in);

    if(!isDebug) {
        cssfile = cssfile.pipe(cssnano());
    }

    return cssfile.pipe(gulp.dest(css.out));
});

Run the minifying task in command line:

$ export NODE_ENV=production
$ gulp