131 lines
5.1 KiB
Python
131 lines
5.1 KiB
Python
"""按项目实际用到的 t-icon 名称,子集化图标字体并重写 icon.wxss。
|
||
|
||
为什么需要这个脚本:
|
||
- tdesign 自带的 icon.wxss 是 485KB:2347 个 `.t-icon-{name}` 规则 + 内嵌的
|
||
278KB base64 字体。凡是 usingComponents 里引了 t-icon 的页面,都要解析这份
|
||
样式并解码字体;真机实测 custom-tab-bar 组件构造因此耗时 59ms。
|
||
- 本项目实际只会用到 40 来个字形,脚本把字体裁到这些字形、把规则裁到这些
|
||
class,产物约 10KB(-95%),视觉与原字体逐字形一致。
|
||
|
||
用法(仓库任意目录执行):
|
||
pip install fonttools
|
||
python tools/build-icon-wxss.py
|
||
|
||
注意:
|
||
1. 微信「构建 npm」会用 node_modules 覆盖 miniprogram_npm/tdesign-miniprogram,
|
||
覆盖后 icon.wxss 退回「远程字体 + 全量 class」,需重新执行本脚本。
|
||
2. 新增图标时先确认 miniprogram_npm/.../icon/icon.wxss 里的 `.t-icon-{name}`
|
||
存在(构建 npm 后是全集),再执行脚本;脚本已扫描全仓库的字符串字面量,
|
||
新名字只要出现在模板 `name="xxx"` 或数据里 `icon: 'xxx'` 就会被带上。
|
||
"""
|
||
|
||
import base64
|
||
import io
|
||
import os
|
||
import re
|
||
import sys
|
||
|
||
try:
|
||
from fontTools import subset
|
||
except ImportError: # pragma: no cover - 只是提示,正常路径不会进来
|
||
sys.exit('缺少依赖:请先执行 pip install fonttools')
|
||
|
||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||
ICON_WXSS = os.path.join(ROOT, 'miniprogram_npm', 'tdesign-miniprogram', 'icon', 'icon.wxss')
|
||
FONT_FILE = os.path.join(ROOT, 'assets', 'fonts', 't.woff')
|
||
|
||
# 只扫业务代码:doc/ 里的说明文本、tools/ 自身和 npm 产物不该参与取词
|
||
SCAN_EXT = ('.js', '.json', '.wxml', '.wxss')
|
||
SKIP_DIRS = {'miniprogram_npm', 'node_modules', 'doc', 'tools', '.git'}
|
||
|
||
ICON_RULE = re.compile(r"\.t-icon-([a-zA-Z0-9_-]+):before\{content:'\\([0-9a-fA-F]{2,6})';\}")
|
||
FONT_FACE = re.compile(r'@font-face\{([^}]*)\}')
|
||
|
||
|
||
def collect_icon_names():
|
||
"""从业务代码里收集可能传给 t-icon 的字面量,再与字体 class 表求交集。"""
|
||
candidates = set()
|
||
for dirpath, dirnames, filenames in os.walk(ROOT):
|
||
dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
|
||
for filename in filenames:
|
||
if not filename.endswith(SCAN_EXT):
|
||
continue
|
||
path = os.path.join(dirpath, filename)
|
||
with io.open(path, 'r', encoding='utf-8', errors='ignore') as handle:
|
||
text = handle.read()
|
||
candidates.update(re.findall(r"'([^'\n]{2,40})'", text))
|
||
candidates.update(re.findall(r'name="([^"{]{2,40})"', text))
|
||
candidates.update(re.findall(r'icon: "([^"\n]{2,40})"', text))
|
||
return candidates
|
||
|
||
|
||
def load_css():
|
||
with io.open(ICON_WXSS, 'r', encoding='utf-8') as handle:
|
||
return handle.read()
|
||
|
||
|
||
def subset_font(codepoints):
|
||
"""把 t.woff 裁到指定码位,返回 woff 字节。"""
|
||
options = subset.Options()
|
||
options.flavor = 'woff'
|
||
options.hinting = False
|
||
options.desubroutinize = True
|
||
options.layout_features = [] # 图标字体不需要 OpenType 排印特性
|
||
font = subset.load_font(FONT_FILE, options)
|
||
subsetter = subset.Subsetter(options=options)
|
||
subsetter.populate(unicodes=codepoints)
|
||
subsetter.subset(font)
|
||
buffer = io.BytesIO()
|
||
subset.save_font(font, buffer, options)
|
||
return buffer.getvalue()
|
||
|
||
|
||
def main():
|
||
css = load_css()
|
||
|
||
mapping = {name: int(code, 16) for name, code in ICON_RULE.findall(css)}
|
||
if not mapping:
|
||
sys.exit('icon.wxss 里没找到 .t-icon-{name}:before 规则,先执行「构建 npm」再跑本脚本')
|
||
|
||
used = sorted(name for name in collect_icon_names() if name in mapping)
|
||
if not used:
|
||
sys.exit('没有从业务代码里扫到任何 t-icon 名称,脚本未做修改')
|
||
|
||
original_css_size = len(css)
|
||
font_bytes = subset_font([mapping[name] for name in used])
|
||
font_base64 = base64.b64encode(font_bytes).decode('ascii')
|
||
|
||
# 1) 替换 @font-face 的 src:全量 base64 → 子集 base64
|
||
face_match = FONT_FACE.search(css)
|
||
if not face_match:
|
||
sys.exit('icon.wxss 里没有 @font-face,无法注入字体')
|
||
family_match = re.search(r'font-family:([^;]+);', face_match.group(1))
|
||
family = family_match.group(1) if family_match else 't'
|
||
new_face = (
|
||
'@font-face{font-family:%s;src:url(data:font/woff;base64,%s) format("woff");}'
|
||
% (family, font_base64)
|
||
)
|
||
css = css[:face_match.start()] + new_face + css[face_match.end():]
|
||
|
||
removed = []
|
||
|
||
def keep_or_drop(match):
|
||
if match.group(1) in used:
|
||
return match.group(0)
|
||
removed.append(match.group(1))
|
||
return ''
|
||
|
||
css = ICON_RULE.sub(keep_or_drop, css)
|
||
|
||
with io.open(ICON_WXSS, 'w', encoding='utf-8') as handle:
|
||
handle.write(css)
|
||
|
||
print('保留图标 %d 个:%s' % (len(used), ', '.join(used)))
|
||
print('删除图标规则 %d 条' % len(removed))
|
||
print('字体 %d -> %d 字节,icon.wxss %d -> %d 字节'
|
||
% (os.path.getsize(FONT_FILE), len(font_bytes), original_css_size, len(css)))
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|