使用gulp在根目录中检查所有HTML文件中的空链接或空白链接。

8

我有很多HTML文档在项目的根目录下。让我们拿一个简单的骨架HTML文档举例:

<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
        <!-- Place favicon.ico in the root directory -->

        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>
        <!--[if lt IE 8]>
            <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->



        <a href="#">hello</a>
        <a href="">hello</a>
        <a href="#">hello</a>
        <a href="">hello</a>
        <a href="#">hello</a>


        <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script src="js/scripts.js"></script>
    </body>
</html>

现在在将这些文件发送给开发团队之前,我被指定任务检查是否存在没有href链接、空href或者带有空片段作为href的链接。也就是说,基本上不能有以下这样的链接:
<a href="">

或者
<a href="#">

或者
 <a>

我找到了这个gulp插件,但是我有一些问题。首先让我们看一下gulp文件:

这个gulp插件

gulp.task("checkDev", function(callback) {
  var options = {
    pageUrls: [
      'http://localhost:8080/Gulp-Test/index.html'
    ],
    checkLinks: true,
    summary: true
  };
  checkPages(console, options, callback);
});

请注意,当您传递选项checkLinks: true时,不仅对于a标签,对于此页面上提到的所有标签都是如此。如果<a>标签为空或只有#或根本不存在,则插件没有问题。
看看我运行gulp任务时会发生什么: 运行gulp插件的结果 因此,我希望仅检查a链接,如果<a>标签没有href、空值或仅有#,则应引发错误或在摘要报告中显示。
最后,请参阅关于如何传递pageUrl(即要检查的页面)的示例gulp文件:
 pageUrls: [
          'http://localhost:8080/Gulp-Test/index.html'
        ],

我该如何让这个插件检查 Gulp-Test 目录下的所有 .html 文件呢?
总结一下我的问题:我该如何让这个插件在发现没有 href 属性、href 属性为空或者为 # 时抛出错误(即在摘要报告中显示),并且告诉它检查一个目录下的所有 .html 文件。

看起来你在最后一次编辑中找到了答案。请查看此选项 https://www.npmjs.com/package/check-pages#noemptyfragments。我建议你回答自己并接受该答案,这样其他人就可以轻松找到它(还有你可以获得甜甜的积分 :))。 - Ronen Ness
@Ness,虽然接近但仍然离我想要实现的目标很远,我已经重新表述了我的问题。 - Alexander Solonik
@Ness 感谢你的建议,但是使用noEmptyFragments: true,只有<a href="#"></a>会失败... 但是<a></a>和<a href=""></a>会通过。 - Alexander Solonik
源代码可在 GitHub 上获取(https://github.com/DavidAnson/check-pages)。我建议下载一份副本并开始编码。 :) - Heretic Monkey
@MikeMcCaughan 我还不是那么专业! ;) ..否则我第一次就不会问这个问题了 lol - Alexander Solonik
显示剩余4条评论
2个回答

4
我被分配任务检查是否存在没有href、空href或空片段的链接。
如果您只需要这些,您实际上不需要任何gulp插件。而且很难找到符合您特定要求的东西。
但是您可以很容易地自己完成。您所需要做的就是:
  1. 使用gulp.src()读取所有要验证的HTML文件。
  2. 使用through2将每个文件传输到自己的函数中。
  3. 使用任何HTML解析器(例如cheerio)解析每个文件。
  4. 在解析的HTML DOM中查找错误链接。
  5. 使用gutil.log()记录错误链接,以便您知道需要修复什么。
  6. 可以抛出gutil.PluginError,使您的构建失败(可选)。

这是一个完全实现上述功能的Gulpfile(在注释中引用了上述要点):

var gulp = require('gulp');
var through = require('through2').obj;
var cheerio = require('cheerio');
var gutil = require('gulp-util');
var path = require('path');

var checkLinks = function() {
  return through(function(file, enc, cb) { // [2]
    var badLinks = [];
    var $ = cheerio.load(file.contents.toString()); // [3]
    $('a').each(function() {
      var $a = $(this);
      if (!$a.attr('href') || $a.attr('href') == '#') { // [4]
        badLinks.push($.html($a));
      }
    });
    if (badLinks.length > 0) {
      var filePath = path.relative(file.cwd, file.path);
      badLinks.forEach(function(badLink) {
        gutil.log(gutil.colors.red(filePath + ': ' + badLink)); // [5]
      });
      throw new gutil.PluginError( 'checkLinks',
        badLinks.length + ' bad links in ' + filePath); // [6]
    }
    cb();
  });
}

gulp.task('checkLinks', function() {
  gulp.src('Gulp-Test/**/*.html') // [1]
    .pipe(checkLinks());
});

使用类似 Gulp-Test/index.html 的文件运行 gulp checkLinks,如下所示...

<html>
<head><title>Test</title></head>
<body>
<a>no href</a>
<a href="">empty href</a>
<a href="#">empty fragment</a>
<a href="#hash">non-empty fragment</a>
<a href="link.html">link</a>
</body>
</html>

...结果会得到以下输出:

[20:01:08] Using gulpfile ~/example/gulpfile.js
[20:01:08] Starting 'checkLinks'...
[20:01:08] Finished 'checkLinks' after 21 ms
[20:01:08] Gulp-Test/index.html: <a>no href</a>
[20:01:08] Gulp-Test/index.html: <a href="">empty href</a>
[20:01:08] Gulp-Test/index.html: <a href="#">empty fragment</a>

/home/sven/example/gulpfile.js:22
      throw new gutil.PluginError( 'checkLinks',
      ^
Error: 3 bad links in Gulp-Test/index.html

1
var gulp = require('gulp');

var jsdom= require('jsdom').jsdom;

var fs=require('fs');

var colors= require('colors');

colors.setTheme({

  error:"red",

  file:"blue",

  info:"green",

  warn:"yellow"
});


gulp.task('checkLinks',function() {


  fs.readdir('.',function(err, files){

    if(err)
      throw err;


    var htmlFiles=files.filter(function(c,i,a){

      return c.substring(c.lastIndexOf('.')+1)==="html";

    });

    htmlFiles.forEach(function(c,i,a){

      fs.readFile(c,function(fileReadErr,data){

        if(fileReadErr)
          throw fileReadErr;

        var doc= jsdom(data);

        var window= doc.defaultView;

        var $=require('jquery')(window);

        var aTags=$('a').toArray(); 

        var k=0;

        console.log(("\n\n************************Checking File "+c+"***************************").info);

        for(var i=0; i<aTags.length; i++){

          if(!(aTags[i].hasAttribute("href")) || aTags[i].getAttribute("href")==="" || aTags[i].getAttribute("href")==="#" ) {

             k++;

             console.log("BAD LINK ".error+aTags[i].outerHTML.info+" IN FILE "+c.file);

          }
        }

        console.log(("BAD-LINKS COUNT IN " +c+" is "+k).bgRed.white);

        window.close();

      });
    });
  });

});

输出:

output of script above


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接