Search code examples
cssgulppostcsscssnano

Optimizing CSS with cssnano advanced transforms using Gulp + PostCSS


My current working gulpfile.js:

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

    gulp.task('css', function () {
        var plugins = [
            cssnano()
        ];
        return gulp.src('css/*.css')
            .pipe(postcss(plugins))
            .pipe(gulp.dest('css/min/'));
    });

Gulp pipes all the CSS to PostCSS which runs them through cssnano, and they all land in css/min. Nice.

How do I get cssnano to use advanced transforms?

Ideally, with vars, or parameter objects instead of extarnal config scripts. I think the anwser might be on this cssnano guide page, but I don't know how to make it work with Gulp+PostCSS.


Solution

  • You can pass options to the cssnano function, so I believe it is a matter of the following:

    var postcss = require('gulp-postcss');
    var gulp = require('gulp');
    var cssnano = require('cssnano');
    
    gulp.task('css', function () {
        var plugins = [
            cssnano({
                preset: ['advanced', {
                    // preset options here, e.g...
                    discardComments: { removeAll: true }
                }]
            })
        ];
        return gulp.src('css/*.css')
            .pipe(postcss(plugins))
            .pipe(gulp.dest('css/min/'));
    });
    

    Obviously ensure you've got cssnano-preset-advanced first via npm install cssnano-preset-advanced --save-dev