简体   繁体   English

Gulp任务无法同步工作

[英]Gulp tasks not working in sync

I'm trying to use browserify with babelify in my project. 我试图用browserifybabelify在我的项目。 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. 据我所知, browserify会通知gulp它已经完成了(非常快,大约10毫秒左右)。 And then js-min moves old file. 然后js-min移动旧文件。 Such observation seems valid because I am always one change behind . 这样的观察似乎是正确的,因为我总是落后一个。

What can I do? 我能做什么?

There are three ways to tell Gulp that a task has finished. 有三种方法可以告诉Gulp任务已完成。

  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. 在2和3两种情况下,Gulp都将等待执行结束,然后再调用下一个函数。 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: 您基本上是在写案例3,但Gulp认为是案例1。要解决此问题,只需返回bundler ,您应该可以:

// 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']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM