---
title: "grunt配置-htmlmin任务"
author: "小丑鱼0703"
date: "2015-04-27T22:17:57Z"
tags: []
categories: ["Web前端"]
slug: "grunt-htmlmin"
draft: false
lastmod: "2015-04-27T22:17:56Z"
id: 2206604
url: "https://wangjingyi.iteye.com/blog/2206604"
---

grunt-contrib-htmlmin插件-tasks目录下htmlmin.js文件中配置了一个htmlmin任务: 
```java
grunt.registerMultiTask('htmlmin', 'Minify HTML', function () {
    var options = this.options();
    grunt.verbose.writeflags(options, 'Options');

    this.files.forEach(function (file) {
      var min;
      var max = file.src.filter(function (filepath) {
        // Warn on and remove invalid source files (if nonull was set).
        if (!grunt.file.exists(filepath)) {
          grunt.log.warn('Source file "' + filepath + '" not found.');
          return false;
        } else {
          return true;
        }
      })
      .map(grunt.file.read)
      .join(grunt.util.normalizelf(grunt.util.linefeed));

      try {
        min = minify(max, options);
      } catch (err) {
        grunt.warn(file.src + '\n' + err);
      }

      if (min.length < 1) {
        grunt.log.warn('Destination not written because minified HTML was empty.');
      } else {
        grunt.file.write(file.dest, min);
        grunt.log.writeln('File ' + file.dest + ' created.');
        helper.minMaxInfo(min, max);
      }
    });
  });
```



```java

htmlmin : {
            dist : {
                options: {                                 
                    removeComments: true, //删除注释
                    collapseWhitespace: true //删除标签间的空格
                },
                files : [{
                    expand : true,
                    cwd : 'app',
                    src : ['*.html'],
                    dest : 'test123'
                }]
            }
        },
```

执行 grunt htmlmin:dist 就可以把app目录下的html文件删除注释和标签间空格压缩到test123目录下。