在所有文件完成gulp任务后运行代码

37

所以我一直在尝试使用Gulp来比较它与Grunt在速度方面的差异,我对结果感到非常印象深刻,但我有一个我不知道如何在Gulp中完成的任务。

所以我有这个gulp任务来压缩HTML:

gulp.task('html-minify', function() {
  var files = [
    relativePaths.webPath + '/*.html',
    relativePaths.webPath + '/components/**/*.html',
    relativePaths.webPath + '/' + relativePaths.appPath + '/components/**/*.html'
  ];

  var changedFiles = buildMetaData.getChangedFiles(files);

  //TODO: needs to execute only after successful run of the task
  buildMetaData.addBuildMetaDataFiles(changedFiles);
  buildMetaData.writeFile();
  return gulp.src(changedFiles, {
      base: relativePaths.webPath
    })
    .pipe(filelog())
    .pipe(minifyHtml({
      empty: true,
      quotes: true,
      conditionals: true,
      comments: true
    }))
    .pipe(gulp.dest(relativePaths.webPath + '/' + relativePaths.appPath +  '/' + relativePaths.buildPath));
});

buildMetaData对象具有我需要的自定义功能,这就是为什么我不能使用像gulp-changed这样的插件。 我正在尝试弄清楚的是如何(如果可能的话)在压缩完成处理所有文件并成功运行后运行一块代码。 使用gulp是否可能实现这样的功能?


1
如果Gulp在所有任务完成后没有发出事件,我会感到非常惊讶和失望。 - Alexander Mills
3个回答

77

您可以创建一个依赖于html-minify的任务:

gulp.task('other-task', ['html-minify'], function() {
  //stuff
});

你也可以在 html-minify 任务中监听流的 end 事件:

gulp.task('html-minify', function(done) {
  var files = [
    relativePaths.webPath + '/*.html',
    relativePaths.webPath + '/components/**/*.html',
    relativePaths.webPath + '/' + relativePaths.appPath + '/components/**/*.html'
  ];

  var changedFiles = buildMetaData.getChangedFiles(files);

  //TODO: needs to execute only after successful run of the task
  buildMetaData.addBuildMetaDataFiles(changedFiles);
  buildMetaData.writeFile();
  var stream = gulp.src(changedFiles, {
      base: relativePaths.webPath
    })
    .pipe(filelog())
    .pipe(minifyHtml({
      empty: true,
      quotes: true,
      conditionals: true,
      comments: true
    }))
    .pipe(gulp.dest(relativePaths.webPath + '/' + relativePaths.appPath +  '/' + relativePaths.buildPath));

  stream.on('end', function() {
    //run some code here
    done();
  });
  stream.on('error', function(err) {
    done(err);
  });
});

2
第二种方法就是我要找的,谢谢。 - ryanzec
7
你可以使用 stream.on('error', done) 来简化代码,无需创建另一个匿名函数,这样可以稍微减少一点工作量。 - Colin
[选项1]中的神奇之处在于调用“other-task”将自动运行“html-minify”,等待其完成,然后再运行自己。谢谢! - Edwin Chua

3
你也可以使用 event-stream 合并两个流。以下示例使用 yargs 从命令行获取输入,构建配置,然后合并两个流:
var enviroment = argv.env || 'development';
gulp('build', function () {
    var config = gulp.src('config/' + enviroment + '.json')
      .on('end', function() { gutil.log(warn('Configured ' + enviroment + ' enviroment.')); })
      .pipe(ngConstant({name: 'app.config'}));
    var scripts = gulp.src('js/*');
    return es.merge(config, scripts)
      .pipe(concat('app.js'))
      .pipe(gulp.dest('app/dist'))
      .on('error', function() { });
  });

除了标准的前置任务外,您还可以等待前一个任务完成。当您需要将参数传递给前置任务时(gulp目前不支持此功能),这非常有用:

var tasks = {
  before: function(arg){
    // do stuff
  },
  build: function() { 
    tasks.before(arg).on('end', function(){ console.log('do stuff') });
  }
};

gulp('build', tasks.build);

3

GULP V3

使用依赖任务:

gulp.task('qr-task', ['md-task', 'js-task'], function() {
  gulp.src(src + '/*.qr')
    .pipe(plugin())
    .pipe(gulp.dest(dist));
});

尽管主任务在所有依赖任务之后开始,但它们(依赖任务)将并行运行(同时进行),因此不要假设任务会按顺序启动/完成(md 和 js 在 qr 之前并行运行)。
如果您想要多个任务的确切顺序且不想将它们拆分,可以使用 async 和 await 来实现此目的:
function Async(p) {
   return new Promise((res, rej) => p.on('error', err => rej(err)).on('end', () => res()));
}

gulp.task('task', async () => {

  await Async(gulp.src(src + '/*.md')
      .pipe(plugin())
      .pipe(gulp.dest(dist)));

  await Async(gulp.src(src + '/*.js')
      .pipe(plugin())
      .pipe(gulp.dest(dist)));

  await Async(gulp.src(src + '/*.qr')
      .pipe(plugin())
      .pipe(gulp.dest(dist)));
});

GULP V4

在Gulp 4中,旧的依赖关系模式已被移除,你会遇到以下错误:

AssertionError [ERR_ASSERTION]: Task function must be specified

你必须使用gulp.parallel和gulp.series(提供正确执行任务)。

gulp.task('qr-task', gulp.series('md-task', 'js-task', function(done) {
  gulp.src(src + '/*.qr')
    .pipe(plugin())
    .pipe(gulp.dest(dist));
  done();
}));

更多细节请访问 https://github.com/gulpjs/gulp/blob/4.0/docs/API.md


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接