Search code examples
javascriptgulp

Gulp watch - execute tasks in order (synchronous)


I have a series of tasks to be run from a watcher but I can get them to fire in order:

Here is the gulp tasks and watcher.

gulp.task('app_scss', function(){
    return gulp.src(appScssDir + '/main.scss')
        .pipe(sass({ style: 'compressed' }).on('error', gutil.log))
        .pipe(autoprefix('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
        .pipe(gulp.dest(appBuilderDir));
});

gulp.task('app_vendor_css', function(){
    return gulp.src(appProviderCssDir + '/*.css')
        .pipe(minifyCSS({ keepSpecialComments: 0 }))
        .pipe(concat('app_vendor.css'))
        .pipe(gulp.dest(appBuilderDir));

});

gulp.task('app_build_css', function(){
    return gulp.src(appBuilderDir + '/*.css')
        .pipe(concat('style.css'))
        .pipe(gulp.dest(targetCssDir));
});


gulp.task('watch', function () {
    gulp.watch(appScssDir + '/**/*.scss', ['app_scss', 'app_build_css']);
});

gulp.task('default', ['app_build_clean', 'app_scss', 'app_vendor_css', 'app_build_css', 'watch']);

So when I update a scss file it should compile them create a single css file. Then the build task concats the file with the vendor files. But every time I save a file its always one step behind. See the video as an example: http://screencast.com/t/065gfTrY

I have renamed the tasks, changed the order in the watch callback etc.

Am I making a obvious mistake?


Solution

  • Gulp starts all tasks at the 'same' time, unless you declare dependencies ( or make streams pipe one to the other ).

    So for example, if you want task app_build_css to wait for tasks app_scss and app_vendor_css to complete, declare the dependencies,

    gulp.task('app_scss', function(){
        return gulp.src(appScssDir + '/main.scss')
            .pipe(sass({ style: 'compressed' }).on('error', gutil.log))
            .pipe(autoprefix('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
            .pipe(gulp.dest(appBuilderDir));
    });
    
    gulp.task('app_vendor_css', function(){
        return gulp.src(appProviderCssDir + '/*.css')
            .pipe(minifyCSS({ keepSpecialComments: 0 }))
            .pipe(concat('app_vendor.css'))
            .pipe(gulp.dest(appBuilderDir));
    
    });
    
    gulp.task('app_build_css', ['app_scss', 'app_vendor_css'], function(){
        return gulp.src(appBuilderDir + '/*.css')
            .pipe(concat('style.css'))
            .pipe(gulp.dest(targetCssDir));
    });
    
    
    gulp.task('watch', function () {
        gulp.watch(appScssDir + '/**/*.scss', ['app_build_css']);
    });
    
    gulp.task('default', ['app_build_clean', 'app_build_css', 'watch']);
    

    Check the Gulp.task() docs