安装依赖

1
2
3
npm install --global gulp-cli #全局安装gulp指令集
npm install gulp --save #安装gulp插件
npm install --save-dev gulp-fontmin

脚本编写

在博客根目录新建gulpfile.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var gulp = require("gulp");
var fontmin = require("gulp-fontmin");

function minifyFont(text, cb) {
gulp
.src("source/font/*.ttf") //原字体所在目录
.pipe(
fontmin({
text: text,
})
)
.pipe(gulp.dest("source/fontdest/")) //压缩后的输出目录
.on("end", cb);
}

gulp.task("mini-font", (cb) => {
var buffers = [];

gulp
.src(["./.deploy_git/**/*.html"]) //HTML文件所在目录请根据自身情况修改
.on("data", function (file) {
buffers.push(file.contents);
})
.on("end", function () {
var text = Buffer.concat(buffers).toString("utf-8");
minifyFont(text, cb);
});
});

gulp.task("default", gulp.parallel("mini-font"));

引入字体到主题文件中

1
2
3
4
5
@font-face {
font-family: "LXGW"; /* 字体名自定义即可 */
src: url("/fontdest/霞鹜文楷.ttf"); /* 字体文件路径 */
font-display: swap;
}

压缩命令

终端输入gulp

1

方法二(推荐)

参考链接

1
2
3
4
5
6
7
8
9
10
11
12
13
pip install fonttools
pyftsubset fang-zheng-hei-ti-gbk.ttf --unicodes-file=sc_unicode.txt

#####

sudo apt-get install -y git g++ make
git clone --recursive https://github.com/google/woff2.git
cd woff2
make clean all

./woff2_compress ../京華老宋体v2.002.subset.ttf
# Processing ../京華老宋体v2.002.subset.ttf => ../京華老宋体v2.002.subset.woff2
# Compressed 4984278 to 3654143.