使用fontmin 进行字体压缩

在页面开发中设计经常会使用一些比较好看的特殊字体,引用完整的中文字体库都比较大,加载性能非常差,所以我们提取部分我们使用到的字体,这样可以把字体文件变成几KB。

fontmin 是一个纯 JavaScript 字体子集化方案,支持提取部分文字、转换字体格式、生成 webfont 和对应 css 样式。

fontmin 安装

官网:http://ecomfe.github.io/fontmin

Github:https://github.com/ecomfe/fontmin

# 安装 
npm install --save fontmin

使用方法

项目根目录创建 trans-fongt.js 文件


const Fontmin = require('fontmin')

exports.transFontfile = (inputFile, outputDir, extractText) => (new Promise((res, rej) => {
  const fontmin = new Fontmin()
    .src(inputFile)
    .use(
      Fontmin.glyph({
        text: extractText,
        hinting: false, // keep ttf hint info (fpgm, prep, cvt). default = true
      })
    )
    .dest(outputDir)
  fontmin.run((err, files) => {
    if (err) {
      rej(err)
    } else {
      res(files)
    }
  })
}))

vue.config.js 中

const { transFontfile } = require('./trans-font') 

// 原生完整的字体文件存放路径
const inputFile = path.resolve(__dirname, 'src/assets/font-input/HuXiaoBo-NanShen.ttf')

// 抽取需要文字之后的字体文件存放路径
const outputDir = path.resolve(__dirname, 'src/assets/font')

// 需要用到的特殊字体文字 例:项目系统名称
const extractText = ${process.env.VUE_APP_BASE_TITLE}

transFontfile(inputFile, outputDir, extractText)

在原字体文件同级目录下创建 font.css 文件,使用 @font-face 引入字体

@font-face {
  font-family: 'HuXiaoBo-NanShen'; /* 重命名字体名 */
  src: url('../font/HuXiaoBo-NanShen.ttf'); /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
  font-weight: normal;
  font-style: normal;
}

主入口文件( main.js/app.vue)中引用 font.css 文件

// main.js中引用

import '@dm/assets/font-input/font.css'

使用

.title {
  margin-right: 106px;
  font-family: HuXiaoBo-NanShen, sans-serif;
  font-size: 24px;
  font-weight: normal;
  color: rgba(255, 255, 255, 90%);
}

.gitignore 忽略切割后的字体文件

/src/assets/font

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值