【问题标题】:Check for empty or blank links in all html files in root directory using gulp使用 gulp 检查根目录中所有 html 文件中的空链接或空白链接
【发布时间】:2016-03-10 09:15:46
【问题描述】:

我的项目根目录中有很多 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>

我找到了this gulp plugin,但我遇到了一些问题。我们先看一下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 标签,还适用于提到的所有标签 on this page。如果&lt;a&gt; 标签为空或只有# 或根本不存在,则插件没有问题。

看看我运行 gulp 任务时会发生什么:

所以我想要的是,如果只能检查 a 链接,并且如果 &lt;a&gt; 标记没有 href 或空白值或只有 #,那么它应该会抛出错误或在摘要报告中显示。

最后,在 gulp 文件的示例中查看我如何传递 pageUrl(即基本上要检查的页面),如下所示:

 pageUrls: [
          'http://localhost:8080/Gulp-Test/index.html'
        ],

我如何让这个插件检查Gulp-Test 目录中的所有.html 文件?

总结一下我的问题:当它看到没有href&lt;a&gt; 或空白的href 或值为# 还有我如何告诉这个插件检查目录中的所有 .html 文件。

【问题讨论】:

  • 看起来您在上次编辑中自己找到了答案。看看这个选项npmjs.com/package/check-pages#noemptyfragments。我建议回答你自己并接受这个答案,这样其他人就可以轻松找到它(而且你也可以得到他们的甜蜜点:))。
  • @Ness 接近但距离我想要实现的目标还有很长的路要走,我已经重新表达了我的问题。
  • @Ness 感谢您的提示,但只有noEmptyFragments: true, 会失败.. 但是 ,将通过。
  • source code is available on GitHub。我建议下载一个副本并开始编码。 :)
  • @MikeMcCaughan 还不是专业人士! ;) .. 否则我不会一开始就问这个问题,哈哈

标签: javascript html gulp


【解决方案1】:

我的任务是检查没有没有 href 和空 href 的链接,或者有一个空片段作为 href。

如果这就是你所需要的,你真的不需要任何 gulp 插件。无论如何,您是否会找到适合您特定要求的东西是值得怀疑的。

但是,您可以很容易地自己完成此操作。你真正需要做的就是:

  1. 使用gulp.src() 读入您要验证的所有 HTML 文件。
  2. 使用through2 将每个文件传递给您自己的函数。
  3. 使用您喜欢的任何 HTML 解析器(例如 cheerio)解析每个文件。
  4. 在已解析的 HTML DOM 中查找错误链接。
  5. 使用gutil.log() 记录错误链接,以便您知道要修复什么。
  6. 可能会抛出一个gutil.PluginError,这样你的构建就会失败(这是可选的)。

这是一个完全可以做到这一点的 Gulpfile(参考 cmets 中的上述几点):

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 checkLinksGulp-Test/index.html ...

<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

【讨论】:

    【解决方案2】:
    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();
    
          });
        });
      });
    
    });
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      • 1970-01-01
      • 2016-12-25
      • 2012-03-31
      • 1970-01-01
      • 2012-02-21
      相关资源
      最近更新 更多