Search code examples
javascriptcssgulpgulp-watch

autoprefixer watch task configuration


Currently I am using Autoprefixer inside of my gulpfile.js. However it only works with a watch task set up! This might be because I am not referencing the return gulp.src('./site/css/*.css') correctly.

Here is how autoprefixer explains how to set up a autoprefixer task

gulp.task('autoprefixer', function () {
    var postcss      = require('gulp-postcss');
    var sourcemaps   = require('gulp-sourcemaps');
    var autoprefixer = require('autoprefixer');

    return gulp.src('./src/*.css')
        .pipe(sourcemaps.init())
        .pipe(postcss([ autoprefixer({ browsers: ['last 2 versions'] }) ]))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./dest'));
});

Here is my autoprefixer task inside of my gulpfile.js

gulp.watch('./site/css/main.css',['autoprefixer']);

gulp.task('autoprefixer',function () {
    var postcss = require('gulp-postcss');
    var sourcemaps = require('gulp-sourcemaps');
    var autoprefixer = require('autoprefixer');

    return gulp.src('./site/css/*.css')
        .pipe(sourcemaps.init())
        .pipe(postcss([ autoprefixer({ browsers: ['> 1%','last 2 versions'] }) ]))
        .pipe(sourcemaps.write('.'))
        .pipe(gulp.dest('./site/css'));
});

Link to the entire gulpfile.js file and the repo that I am working with.


Solution

  • You can call your autoprefixer task directly by executing gulp autoprefixer from the cmd line or you can add it as a dependency of another task. Like this:

    gulp.task('someTask', ['autoprefixer'], function () {
        //  Do stuff
    });
    

    See the relevant bit of documentation here.

    Edited

    The autoprefixer task will get executed BEFORE its dependent task does ('someTask' in my example), so be aware of your execution flow here.