防止 gulp-htmllint 跳过无效的 html 文件

Prevent gulp-htmllint from skipping invalid html files

我正在使用 gulp-htmllint 检查包含 html 个片段的文件。然而,令我惊讶的是,它 跳过 带有无效标记的文件。我很想 "as good as possible" linting,但至少 我希望它失败/报告无效 html.

错误

这是一个重现。首先是 gulpfile.js(事先需要适当的 npm install 命令):

var gulp = require("gulp"),
    gutil = require('gulp-util'),
    htmllint = require("gulp-htmllint"), 
    path = require('path');

gulp.task("default", [], function() {
    return gulp.src("src/*.html")
        .pipe(htmllint({}, reporter));
});

function reporter(filepath, issues) {
    var filename = path.basename(filepath);
    if (issues.length > 0) {
        issues.forEach(function (issue) {
            gutil.log(gutil.colors.cyan('[lintHtml] ') + gutil.colors.white(filename + ' [' + issue.line + ',' + issue.column + ']: ') + gutil.colors.red('(' + issue.code + ') ' + issue.msg));
        });
        process.exitCode = 1;
    }
}

reporter 基于程序包主页上的示例。

有了这个 src/fragment.html 文件:

<span style="color: red;">Test 1.</span>
<span style="color: green;">Test 2.</span>

我会很好地得到:

[08:04:06] Using gulpfile ~\myapp\gulpfile.js
[08:04:06] Starting 'default'...
[08:04:06] [lintHtml] fragment.html [1,6]: (E001) the `style` attribute is banned
[08:04:06] [lintHtml] fragment.html [2,6]: (E001) the `style` attribute is banned
[08:04:06] Finished 'default' after 38 ms

但是,如果我像这样使 html 文件无效:

<span style="color: red;"Test 1.</span>
<span style="color: green;">Test 2.</span>

我得到:

[08:05:06] Using gulpfile ~\myapp\gulpfile.js
[08:05:06] Starting 'default'...
[08:05:06] Finished 'default' after 25 ms

好像没什么事一样

当我的片段出现此类问题时,如何让进程报告错误并失败?

PS。我结束了 cross-posting to Github as an issue too.

如果不更改 gulp-htmllint 本身,就无法做到这一点。如果您查看 source,您会发现它只为 htmllint 承诺提供成功处理程序:

lint.then(function(issues) {
    issues.forEach(function(issue) {
        issue.msg = issue.msg || htmllint.messages.renderIssue(issue);
    });
    reporter(file.path, issues);
});

要输出 linting 过程因无效 html 而失败的情况,它还必须提供拒绝处理程序:

lint.then(function(issues) {
    issues.forEach(function(issue) {
        issue.msg = issue.msg || htmllint.messages.renderIssue(issue);
    });
    reporter(file.path, issues);
}).catch(function(error) {
    //do something useful here
    console.log(file.path + ': ' + error.toString());
});

这意味着您有两个选择: