How to run Gulp tasks sequentially one after the other

前端 未结 14 945
眼角桃花
眼角桃花 2020-11-22 13:00

in the snippet like this:

gulp.task \"coffee\", ->
    gulp.src(\"src/server/**/*.coffee\")
        .pipe(coffee {bare: true}).on(\"error\",gutil.log)
           


        
14条回答
  •  深忆病人
    2020-11-22 13:15

    run-sequence is the most clear way (at least until Gulp 4.0 is released)

    With run-sequence, your task will look like this:

    var sequence = require('run-sequence');
    /* ... */
    gulp.task('develop', function (done) {
        sequence('clean', 'coffee', done);
    });
    

    But if you (for some reason) prefer not using it, gulp.start method will help:

    gulp.task('develop', ['clean'], function (done) {
        gulp.on('task_stop', function (event) {
            if (event.task === 'coffee') {
                done();
            }
        });
        gulp.start('coffee');
    });
    

    Note: If you only start task without listening to result, develop task will finish earlier than coffee, and that may be confusing.

    You may also remove event listener when not needed

    gulp.task('develop', ['clean'], function (done) {
        function onFinish(event) {
            if (event.task === 'coffee') {
                gulp.removeListener('task_stop', onFinish);
                done();
            }
        }
        gulp.on('task_stop', onFinish);
        gulp.start('coffee');
    });
    

    Consider there is also task_err event you may want to listen to. task_stop is triggered on successful finish, while task_err appears when there is some error.

    You may also wonder why there is no official documentation for gulp.start(). This answer from gulp member explains the things:

    gulp.start is undocumented on purpose because it can lead to complicated build files and we don't want people using it

    (source: https://github.com/gulpjs/gulp/issues/426#issuecomment-41208007)

提交回复
热议问题