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

Jer*_*oen 2 html gulp htmllint

我正在使用gulp-htmllint检查带有html片段的文件.但令我惊讶的是,它会跳过带有无效标记的文件.我希望得到"尽可能好"的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

reporter基于断包的主页上的例子.

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

<span style="color: red;">Test 1.</span>
<span style="color: green;">Test 2.</span>
Run Code Online (Sandbox Code Playgroud)

我很高兴得到:

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

但是,如果我使html文件无效,如下:

<span style="color: red;"Test 1.</span>
<span style="color: green;">Test 2.</span>
Run Code Online (Sandbox Code Playgroud)

我明白了:

[08:05:06] Using gulpfile ~\myapp\gulpfile.js
[08:05:06] Starting 'default'...
[08:05:06] Finished 'default' after 25 ms
Run Code Online (Sandbox Code Playgroud)

好像没有错.

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

PS.我最终也将问题交叉发布到Github.

Sve*_*ung 5

没有改变gulp-htmllint本身就没有办法做到这一点.如果查看源代码,您会发现它只为htmllint承诺提供了成功处理程序:

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

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

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

这意味着您有两种选择:

  • 感谢您的评论(以及解决方案:-)).我已经实现了这个并发布了gulp-htmllint的0.0.7版本. (2认同)