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

时间:2016-03-10 09:15:47

标签: javascript html gulp

我的项目根目录中有很多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提及的所有标记。如果<a>标记为空或只有#或根本不存在,则插件不会出现问题。

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

The result of running the gulp plugin

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

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

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

如何告诉此插件检查.html目录中的所有Gulp-Test文件?

总结一下我的问题:如何看到<a>没有href或者href为空白时,如何让这个插件抛出错误(即在摘要报告中显示)值为#以及如何告诉此插件检查目录中的所有.html文件。

2 个答案:

答案 0 :(得分:4)

  

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

如果您需要,那么您根本不需要任何gulp插件。无论如何,你会发现一些符合你特定要求的东西,这是值得怀疑的。

然而,你可以很容易地完成这个任务。你真正需要做的就是:

  1. 使用gulp.src()读取您要验证的所有HTML文件。
  2. 使用through2将每个文件传输到您自己的函数。
  3. 使用您喜欢的任何HTML解析器解析每个文件(例如cheerio)。
  4. 在已解析的HTML DOM中找到错误的链接。
  5. 使用gutil.log()记录错误链接,以便了解要解决的问题。
  6. 可能会抛出gutil.PluginError,因此您的构建失败(这是可选的)。
  7. 这是一个Gulp文件,它正是这样做的(参考评论中的上述几点):

    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 checkLinks正常运行Gulp-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
    

答案 1 :(得分: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