gulp-htmlmin压缩html的gulp插件实例代码

时间:2016-06-06    点击:125   

通过一条命令用Npm安装gulp-htmlmin:

npm install gulp-htmlmin --save-dev

  安装完毕后,打开gulpfile.js文件,我们里面编写一个task用来专门压缩html,并对html进行一系列的处理:

var gulp = require('gulp');
var htmlmin = require('gulp-htmlmin');
gulp.task('html',function(){
var options = {
collapseWhitespace:true,
collapseBooleanAttributes:true,
removeComments:true,
removeEmptyAttributes:true,
removeScriptTypeAttributes:true,
removeStyleLinkTypeAttributes:true,
minifyJS:true,
minifyCSS:true 
};
gulp.src('app/**/*.html')
.pipe(htmlmin(options))
.pipe(gulp.dest('dest/')); 
}); 

  我们看到task里面有个设置选项,分别介绍一下他们的属性的作用:

1.collapseWhitespace:从字面意思应该可以看出来,清除空格,压缩html,这一条比较重要,作用比较大,引起的改变压缩量也特别大;

2.collapseBooleanAttributes:省略布尔属性的值,比如:<input checked="checked"/>,那么设置这个属性后,就会变成 <input checked/>;

3.removeComments:清除html中注释的部分,我们应该减少html页面中的注释。

4.removeEmptyAttributes:清除所有的空属性,

5.removeSciptTypeAttributes:清除所有script标签中的type="text/javascript"属性。

6.removeStyleLinkTypeAttributes:清楚所有Link标签上的type属性。

7.minifyJS:压缩html中的javascript代码。

8.minifyCSS:压缩html中的css代码。

  总之,压缩Html的原则就是清除没用的代码,删除本就默认值的属性,将html压缩的最小,这样才能提高项目运行的性能。

深入理解逻辑表达式的用法 与或非的用法
逻辑表达式中与或非的用法详解
node.js 中国天气预报 简单实现
nodejs 的 session 简单使用
node.js cookie-parser之parser.js
> 返回     
地址:上海市普陀区胶州路941号长久商务中心 电话: QQ:
© Copyright 2012 上海网络 Product All Rights Reserved