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

jba*_*ndi 1 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/"));
});
Run Code Online (Sandbox Code Playgroud)

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

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

Ben*_*Ben 6

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

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

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

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

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