此次項目中UI小姐姐要求用平方等其餘字體,遂引入了這些字體,打包的時候發現,OMG,一個字體文件居然要10M,實在不能忍,因而開始了字體文件大小的優化實踐,最後變成38KB一個,還行吧。css
可能存在的坑!!!html
安裝node
npm install gulp-font-spider --save-dev
複製代碼
CSSpython
// html沒什麼特別的,引入CSS文件的時候路徑注意就行了
@charset "UTF-8";
// 注意引入時使用相對路徑
@font-face {
font-family: 'pinghei';
src: url('../../assets/font/pinghei.eot');
src:
url('../../assets/font/pinghei.eot?#font-spider') format('embedded-opentype'),
url('../../assets/font/pinghei.woff') format('woff'),
url('../../assets/font/pinghei.ttf') format('truetype'), // 只要確保運行時這個ttf文件在就行了,其它不用管
url('../../assets/font/pinghei.svg') format('svg');
font-weight: normal;
font-style: normal;
}
body {
font-family: pinghei; //使用字體
}
複製代碼
gulpfile.jsgit
/** * 此爲gulp4.0的配置文件 */
var gulp = require('gulp'),
fontSpider = require( 'gulp-font-spider'); //字體文件優化--字蛛
/** * fontSpider */
gulp.task('fontSpider', done => {
gulp
.src(buildPath.html) // 引入相應的html文件
.pipe(fontSpider({
backup: false // 不備份源字體,默認開啓備份
}))
.pipe(notify({
message: "font compress done" // 完成後通知
}))
done(); //結束這個task
});
/** * gulp 默認指令 */
// 其實開發階段無所謂壓不壓縮字體,因此開發階段,我只是將源字體copy過去便可
/** * gulp build * 這裏我將fontSpider這個task在最後執行,由於這樣確保打包後的html和css文件都已存在了, * 此時在針對編譯後的dist裏的html文件裏進行篩選字體文件壓縮,這樣更有效 */
gulp.task('build',
gulp.series('clean', 'styles', 'html', // 串行運行
gulp.parallel('js', 'vendor', 'copyAssets'), //並行運行
'fontSpider') //最後運行
);
複製代碼
gulp buildgithub
文件夾檢查(若是開啓備份,則源字體文件在.font-spider中,圖中我關閉了天然沒有)npm
可能存在的坑!!!gulp
安裝bash
npm install font-spider -g
複製代碼
運行app
font-spider ./*.html --debug
複製代碼
應用版安裝
截圖