標籤:
通過一條命令用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壓縮的最小,這樣才能提高項目啟動並執行效能。
gulp-htmlmin壓縮html