20

我尝试干燥我的 gulpfile。那里有一些我不喜欢的代码重复。怎样才能做得更好?

gulp.task('scripts', function() {
  return gulp.src('src/scripts/**/*.coffee')
    .pipe(coffeelint())
    .pipe(coffeelint.reporter())
    .pipe(coffee())
    .pipe(gulp.dest('dist/scripts/'))
    .pipe(gulp.src('src/index.html'))  // this
    .pipe(includeSource())             // needs
    .pipe(gulp.dest('dist/'))          // DRY
});

gulp.task('index', function() {
  return gulp.src('src/index.html')
    .pipe(includeSource())
    .pipe(gulp.dest('dist/'))
});

我得到了index一个单独的任务,因为我需要观看src/index.htmllivereload。但我也在关注我的.coffee资源,当它们发生变化时,我也需要更新src/index.html

我如何通过管道index输入scripts

4

2 回答 2

25

gulp使您能够根据参数对一系列任务进行排序。

例子:

gulp.task('second', ['first'], function() {
   // this occurs after 'first' finishes
});

尝试以下代码,您将运行任务“索引”来运行这两个任务:

gulp.task('scripts', function() {
  return gulp.src('src/scripts/**/*.coffee')
    .pipe(coffeelint())
    .pipe(coffeelint.reporter())
    .pipe(coffee())
    .pipe(gulp.dest('dist/scripts/'));
});

gulp.task('index', ['scripts'], function() {
  return gulp.src('src/index.html')
    .pipe(includeSource())
    .pipe(gulp.dest('dist/'))
});

该任务index现在需要scripts在运行其函数内的代码之前完成。

于 2014-05-06T21:11:18.753 回答
3

如果您查看 Orchestrator 源代码,特别是.start()实现,您会看到如果最后一个参数是一个函数,它将把它视为一个回调。

我为自己的任务编写了这个片段:

  gulp.task( 'task1', () => console.log(a) )
  gulp.task( 'task2', () => console.log(a) )
  gulp.task( 'task3', () => console.log(a) )
  gulp.task( 'task4', () => console.log(a) )
  gulp.task( 'task5', () => console.log(a) )

  function runSequential( tasks ) {
    if( !tasks || tasks.length <= 0 ) return;

    const task = tasks[0];
    gulp.start( task, () => {
        console.log( `${task} finished` );
        runSequential( tasks.slice(1) );
    } );
  }
  gulp.task( "run-all", () => runSequential([ "task1", "task2", "task3", "task4", "task5" ));
于 2017-05-24T22:22:34.347 回答