如何使用Gulp进行正确的错误处理?

时间:2015-01-09 01:43:20

标签: gulp

使用Gulp很容易编排一个由通过管道处理的许多小步骤组成的构建。

我目前的Gulp设置中的任务之一如下:

gulp.task("release-assets", ["angular-templates", "less-compile"], function() {
    var assets = useref.assets();
    var jsFilter = filter("**/*.js");
    var moonwalkFilter = filter("**/" + MOONWALK_JS);
    var cssFilter = filter("**/*.css");

    return gulp.src("./Content/**/*.cshtml")
        .pipe(assets)               // Concatenate with gulp-useref
        .pipe(jsFilter)
        .pipe(ngAnnotate())         // Process javascript sources to add dependency injection annotations
        .pipe(uglify())             // Minify javascript sources
        .pipe(jsFilter.restore())
        .pipe(cssFilter)
        .pipe(less())               // Generate CSS from LESS
        .pipe(cmq({ log: true }))   // Combine matching media queries into one media query definition
        .pipe(minifyCSS())          // Minify CSS sources
        .pipe(cssFilter.restore())
        .pipe(moonwalkFilter)       // Filter the moonwalk.js source file, which is generated above by useref
        .pipe(addsrc("Temp/" + TEMPLATES_JS))// Add the templates.js to the stream, which is generated by a seperate task
        .pipe(order(["**/" + MOONWALK_JS, "*.js"]))// Order stream, so that templates.js is appended to moonwalk.js (needed, since templates depend on the angular module)
        .pipe(concat(MOONWALK_JS))// Concat the existing moonwalk.js and the templates.js into moonwalk.js
        .pipe(moonwalkFilter.restore())
        .pipe(rev())                // Rename the concatenated files
        .pipe(assets.restore())
        .pipe(useref())             // Replace the original references in the cshtml with the concatenated and processed resources by usemin
        .pipe(revReplace({replaceInExtensions:[".cshtml"]}))         // Replace the usemin generated resources with the reved resources
        .pipe(gulp.dest("Dist/"));
});

如何在此任务中进行正确的错误处理? 我想要的是: - 如果任务的某个依赖项失败,则构建应该失败 - 构建失败并报告有意义的错误,此任务中的一个步骤会产生错误。

据我所知,我必须自己关心管道/流中的错误处理......我该怎么做? 在管道的每一步之后我真的必须包含on("error", errorHandler)吗? 在Gulp中是否有关于错误处理的文档?

1 个答案:

答案 0 :(得分:6)

  

我真的必须在管道中的每一步之后包含一个on(“error”,errorHandler)吗?

是的,除非您使用可以将所有这些错误事件合并为一个的模块。看看stream-combiner,它可以做到这一点。 gulp文档中有一个示例配方,它使用此模块来监听管道中的错误:

var combiner = require('stream-combiner2');
var uglify = require('gulp-uglify');
var gulp = require('gulp');

gulp.task('test', function() {
  var combined = combiner.obj([
    gulp.src('bootstrap/js/*.js'),
    uglify(),
    gulp.dest('public/bootstrap')
  ]);

  // any errors in the above streams will get caught
  // by this listener, instead of being thrown:
  combined.on('error', console.error.bind(console));

  return combined;
});

https://github.com/gulpjs/gulp/blob/master/docs/recipes/combining-streams-to-handle-errors.md

因此,如示例所示,使用组合器包装流,您将拥有一个错误处理程序。