Tomek Buszewski
Tomek Buszewski

Reputation: 7935

Gulp tasks not working in sync

I'm trying to use browserify with babelify in my project. Everything works great except the problem of sync.

// Browserify
//---------------------------------------------------
gulp.task('browserify', function() {
    var bundler = browserify('_babel/script.js').transform(babelify);

    bundler.bundle()
        .pipe(source('_babel/script.js'))
        .pipe(gulp.dest('_dev'));
});

// JavaScript moving and merging
//---------------------------------------------------
gulp.task('js-min', ['browserify'], function() {
    return gulp.src('_dev/_babel/script.js')
        .pipe(concatjs('scripts.js'))
        .pipe(gulp.dest('_js'))
        .pipe(browserSync.stream());
});

gulp.watch('_babel/**', ['js-min']);

From what I can tell, browserify notifies gulp that it's done (it's done very quic, 10 ms or so) when it's not. And then js-min moves old file. Such observation seems valid because I am always one change behind.

What can I do?

Upvotes: 1

Views: 104

Answers (1)

MarcoL
MarcoL

Reputation: 9989

There are three ways to tell Gulp that a task has finished.

  1. You have all sync stuff to execute in the task:

     gulp.task('task-a', function(){
       // do sync stuff
    
       // you may return here
       // but because everything is sync Gulp assumes that everything has ended
     });
    
  2. You get the callback as input

    // the passed cb is the next task to execute
    gulp.task('task-b', function(cb){
    
      // do async stuff
    
      cb( result );
    });
    
  3. Return a promise/stream (which fits your case):

    gulp.task('task-c', function(){
    
      // return either a promise or a stream
      return gulp.src( ... );
    

    });

In both cases 2 and 3 Gulp will wait the end of the execution before calling the next function. You are basically writing a case 3 but Gulp believes it's 1. To fix this just return the bundler and you should be fine:

// Browserify
//---------------------------------------------------
gulp.task('browserify', function() {
  var bundler = browserify('_babel/script.js').transform(babelify);

  return bundler.bundle()
    .pipe(source('_babel/script.js'))
    .pipe(gulp.dest('_dev'));
});

// JavaScript moving and merging
//---------------------------------------------------
gulp.task('js-min', ['browserify'], function() {
  return gulp.src('_dev/_babel/script.js')
    .pipe(concatjs('scripts.js'))
    .pipe(gulp.dest('_js'))
    .pipe(browserSync.stream());
});

gulp.watch('_babel/**', ['js-min']);

Upvotes: 2

Related Questions