温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

gulp-font-spider如何实现中文字体包压缩

发布时间:2023-03-16 14:18:26 来源:亿速云 阅读:118 作者:iii 栏目:开发技术

这篇文章主要讲解了“gulp-font-spider如何实现中文字体包压缩”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“gulp-font-spider如何实现中文字体包压缩”吧!

1.背景

在前端开发中,经常需要使用特定的字体包,但由于中文字体包特别大,严重影响网页的加载速度,所以需要对字体包进行压缩。

2.方法

提取项目中使用到的汉字,并利用gulp-font-spider来实现ttf格式字体包的压缩,并生成eot,svg,woff等其他格式的字体包,其中使用gulp来实现这一流程的自动化。

3.gulp-font-spider 安装及使用

字蛛是一个中文 WebFont 自动化压缩工具,它能自动分析页面使用的 WebFont 并进行按需压缩,无需手工配置。

3.1 特性

  • 按需压缩:从原字体中剔除没有用到的字符,可以将数 MB 大小的中文字体压缩成几十 KB

  • 简单可靠:完全基于 HTML 与 CSS 分析进行本地处理,无需 js 与服务端辅助

  • 自动转码:将字体转码成所有浏览器支持的格式,包括老旧的 IE6 与现代浏览器

  • 图标字体:除了常规的字体支持外,还支持图标字体(字蛛 v1.0.0 新特性)

3.2 安装

npm install gulp-font-spider --save-dev

3.2 使用范例

var gulp = require( 'gulp' );
var fontSpider = require( 'gulp-font-spider' );
gulp.task('fontspider', function() {
    return gulp.src('./index.html')
        .pipe(fontSpider());
});
gulp.task('defualt', ['fontspider']);

推荐的跨浏览器 @font-faceCSS 写法:

/* html中 声明 WebFont*/
@font-face {
  font-family: 'pinghei';
  src: url('../font/pinghei.eot');
  src: 
    url('../font/pinghei.eot?#font-spider') format('embedded-opentype'),
    url('../font/pinghei.woff') format('woff'),
    url('../font/pinghei.ttf') format('truetype'),
    url('../font/pinghei.svg') format('svg');
  font-weight: normal;
  font-style: normal;
}
/*使用选择器指定字体*/
.home h3, .demo > .test {
    font-family: 'pinghei';
}

特别说明: @font-face中的 src定义的 .ttf 文件必须存在,其余的格式将由工具自动生成

font-spider [options] <htmlFile1 htmlFile2 ...>

3.3 使用场景限制

  • 仅支持固定的文本与样式,不支持 javascript 动态插入的元素与样式

  • .otf 字体需要转换成 .ttf 才能被压缩

  • 仅支持 utf-8 编码的 HTML 与 CSS 文件

  • CSS content 属性只支持普通文本,不支持属性、计数器等特性

4. 自动化流程主要步骤

4.1.提取项目中使用到的汉字

利用through3插件,将业务文件夹src内所有的汉字提取出来,并生成chars.txt文件暂存。

gulp.task('extract', () => {
    return gulp.src('src/**/*{.vue,.scss,.ts}', { dot: true }).pipe(concat('chars.txt'))
        .pipe(through3.obj(function (file, enc, callback) {
            const { contents } = file;
            let text = contents.toString();
            var result = text.match(/[\u4e00-\u9fa5]/ig)?.join('');
            if (result){
                file.contents = Buffer.from(result)
                this.push(file);
            }
            callback();
        })).pipe(gulp.dest('fontMinify/'))
});

4.2 生成字蛛所需的html入口文件

读取上一步生成的chars.txt中的汉字,组装html文件,写入字体文件引入样式,并将提取出的汉字插入html中

gulp.task('insertCharactersToHtml', () => {
    return gulp.src('fontminify/chars.txt').pipe(concat('fontMin.html'))
        .pipe(through3.obj(function (file, enc, callback) {
            const { contents } = file;
            let text = contents.toString();
            if (text){
                file.contents = Buffer.from(`<!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <style>
                            @font-face {
                                font-family: 'fz';
                                src: url('${fontName}.eot');
                                src: url('${fontName}.eot?#font-spider') format('embedded-opentype'),
                                    url('${fontName}.woff') format('woff'),
                                    url('${fontName}.ttf') format('truetype'),
                                    url('${fontName}.svg') format('svg');
                                font-weight: normal;
                                font-style: normal;
                            }
                            /*使用选择器指定字体*/
                            #app {
                                font-family: 'fz';
                            }
                        </style>
                    </head>
                    <body>
                        <div id="app">
                        ${text}
                        </div>
                    </body>
                    </html>`);
                this.push(file);
            }
            callback();
        })).pipe(gulp.dest('fontMinify'))
});

4.3 利用字蛛执行压缩任务

gulp.task('fontspider', function () {
    return gulp.src('./fontMinify/fontMin.html')
        .pipe(fontSpider());
});

5. 完整代码及目录

5.1 目录结构

gulp-font-spider如何实现中文字体包压缩

5.2 完整代码

实现提取文字,压缩字体包后,移动到静态资源文件夹public下并删除任务中生成的fontMInify文件

const gulp = require('gulp')
const through3 = require("through3");
const del = require('del');
const concat = require('gulp-concat');
const fontSpider = require('gulp-font-spider');
let fontName = 'FZMWFont'
gulp.task('genFontMinify', () => {
    return gulp.src(`public/originalFont/${fontName}.ttf`).pipe(gulp.dest('fontMinify/'))
});
// 提取项目中的汉字
gulp.task('extract', () => {
    return gulp.src('src/**/*{.vue,.scss,.ts}', { dot: true }).pipe(concat('chars.txt'))
        .pipe(through3.obj(function (file, enc, callback) {
            const { contents } = file;
            let text = contents.toString();
            var result = text.match(/[\u4e00-\u9fa5]/ig)?.join('');
            if (result){
                file.contents = Buffer.from(result)
                this.push(file);
            }
            callback();
        })).pipe(gulp.dest('fontMinify/'))
});
// 将提取出的汉字插入模版html中
gulp.task('insertCharactersToHtml', () => {
    return gulp.src('fontminify/chars.txt').pipe(concat('fontMin.html'))
        .pipe(through3.obj(function (file, enc, callback) {
            const { contents } = file;
            let text = contents.toString();
            if (text){
                file.contents = Buffer.from(`<!DOCTYPE html>
                    <html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <style>
                            @font-face {
                                font-family: 'fz';
                                src: url('${fontName}.eot');
                                src: url('${fontName}.eot?#font-spider') format('embedded-opentype'),
                                    url('${fontName}.woff') format('woff'),
                                    url('${fontName}.ttf') format('truetype'),
                                    url('${fontName}.svg') format('svg');
                                font-weight: normal;
                                font-style: normal;
                            }
                            #app {
                                font-family: 'fz';
                            }
                        </style>
                    </head>
                    <body>
                        <div id="app">
                        ${text}
                        </div>
                    </body>
                    </html>`);
                this.push(file);
            }
            callback();
        })).pipe(gulp.dest('fontMinify'))
});
// 字体文件压缩
gulp.task('fontspider', function () {
    return gulp.src('./fontMinify/fontMin.html')
        .pipe(fontSpider());
});
// 将生成后的字体文件移动到预定的静态资源目录
gulp.task('mvMinifyFontToPublic', function () {
    return gulp.src(`./fontMinify/${fontName}.*`)
        .pipe(gulp.dest('public/fonts'));
});
// 删除字体压缩文件产生的中间文件
gulp.task('rmFontMinify', function () {
    return del('fontMinify')
});
gulp.task('default', gulp.series('genFontMinify','extract', 'insertCharactersToHtml', 'fontspider', 'mvMinifyFontToPublic','rmFontMinify'))

6.优缺点

6.1 优点

如上介绍,可以实现字体文件的压缩并生成多种格式字体包,本文使用的字体包从5M压缩到了200K,体积大大减小,并且可以通过gulp.watch监听src文件夹的变动来实现这一流程的自动化

6.2 缺点

目前gulp-font-spider只能实现提取项目中出现的汉字,对于后端接口返回的动态汉字无法提取,只能预先列举可能使用的汉字来使用

感谢各位的阅读,以上就是“gulp-font-spider如何实现中文字体包压缩”的内容了,经过本文的学习后,相信大家对gulp-font-spider如何实现中文字体包压缩这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI