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

rya*_*zec 34 build node.js gulp

所以我一直在尝试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));
});
Run Code Online (Sandbox Code Playgroud)

buildMetaData对象具有我需要的自定义功能以及为什么我不能使用gulp-changed等插件.我想弄清楚的是,在minify完成后如何(如果可能的话)运行一段代码处理所有文件并且它成功运行.吞咽这样的事情有可能吗?

Ben*_*Ben 69

你可以做一个取决于的任务html-minify:

gulp.task('other-task', ['html-minify'], function() {
  //stuff
});
Run Code Online (Sandbox Code Playgroud)

您还可以endhtml-minify任务中侦听流事件:

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);
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 你可以做`stream.on('错误',完成);`来简化它是一个微不足道的数量.无需创建另一个匿名函数. (6认同)
  • 第二种方法就是我想要的,谢谢. (2认同)