通過一條命令用Npm安裝gulp-htmlmin:
npm install gulp-htmlmin --save-dev
安裝完畢后,打開gulpfile.js文件,我們里面編寫一個task用來專門壓縮html,并對html進(jìn)行一系列的處理:
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里面有個設(shè)置選項,分別介紹一下他們的屬性的作用:
1.collapseWhitespace:從字面意思應(yīng)該可以看出來,清除空格,壓縮html,這一條比較重要,作用比較大,引起的改變壓縮量也特別大;
2.collapseBooleanAttributes:省略布爾屬性的值,比如:<input checked="checked"/>,那么設(shè)置這個屬性后,就會變成 <input checked/>;
3.removeComments:清除html中注釋的部分,我們應(yīng)該減少html頁面中的注釋。
4.removeEmptyAttributes:清除所有的空屬性,
5.removeSciptTypeAttributes:清除所有script標(biāo)簽中的type="text/javascript"屬性。
6.removeStyleLinkTypeAttributes:清楚所有Link標(biāo)簽上的type屬性。
7.minifyJS:壓縮html中的javascript代碼。
8.minifyCSS:壓縮html中的css代碼。
總之,壓縮Html的原則就是清除沒用的代碼,刪除本就默認(rèn)值的屬性,將html壓縮的最小,這樣才能提高項目運行的性能。
新聞熱點
疑難解答