Chinese Font Subsetting + Missing Glyph Verification
Chinese fonts are typically 10–20 MB and cannot be sent to the frontend as-is. The industry standard practice is subsetting: only extract the Chinese characters actually used in the project, discarding the rest. For a project with 995 Chinese characters, actual measurements show:
Noto Sans SC variable full font 16.9 MB → subset woff2 275 KB (~367 KB after base64 inline)
Volume reduction of 98%, and no longer dependent on any CDN (embedded inline — no external links, no cross-origin issues, no privacy risks).
But subsetting alone can break: modifying a sentence, importing a table with Chinese data, or even writing a Chinese comment can introduce characters not in the font table — the result is a small number of characters displayed as empty boxes, which are hard to self-check. So this toolset must be a two-part set: rebuild (subset) + measured check (check), where the check can be attached to CI.
When to Use
- Your frontend project needs to embed Chinese fonts (mini programs / H5 / Electron / PWA / single-page inline)
- After changing Chinese copy, you need to confirm "no characters appear as boxes"
- You want to turn "missing characters" into a red/green status in CI, rather than relying on human eyes post-release
- Your project already has a
var ZH = 'data:font/woff2;base64,…'and you need to update it in-place after copy changes
30-Second Quickstart
# Dependencies (only these two: fonttools to read/write fonts, brotli to handle woff2)
python3.12 -m pip install fonttools brotli
# 0) Self-test first: no system fonts, no network, creates a test font with only a few Chinese characters, runs full pipeline
python3.12 scripts/selftest.py # Expected: prints ALL PASS
# 1) Only see how many characters are missing, don't write files
python3.12 scripts/subset_cjk.py ./app --src C:/Windows/Fonts/NotoSansSC-VF.ttf --dry-run
# 2) Generate woff2 file (H5 / Electron)
python3.12 scripts/subset_cjk.py ./app --src <source font> --mode file
# 3) Generate @font-face + base64 CSS (single self-contained file)
python3.12 scripts/subset_cjk.py ./app --src <source font> --mode css --family MyCJK
# 4) Rewrite existing project's fonts.js
python3.12 scripts/subset_cjk.py ./app --src <source font> --mode inject \
--target app/data/fonts.js --var ZH
# 5) Re-verify (separate script, stricter criteria) — this is the real "are there boxes?" judge
python3.12 scripts/check_cmap.py ./app --fonts app/data/fonts.js --var ZH
Exit code of check_cmap.py: 0 = no missing characters, 1 = missing characters (can be directly attached to CI / pre-commit).
Why Two Scripts with Two Different Scopes
| Script | Scope | Rationale |
|---|---|---|
subset_cjk.py | Rebuild scope: skips only full-line // and block comments; Chinese in trailing comments is included | Rebuild must err on the side of including more characters — one extra character costs a few KB at most, but one missing character is an online box |
check_cmap.py | Strict scope: removes all // and /* */ (preserves Chinese in string literals, don't break 'https://…') | Check must err on the side of being strict — a false positive just makes you look, but a false negative is an incident |
⚠️ Comparing only counts will definitely miss issues. The most common false green light is "code uses 871 characters / font table 878 ✓ no missing characters" — sufficient count ≠ sufficient characters. Real incident: count check passed entirely, yet real device still showed 7 characters as boxes (all from two newly merged pages). The only reliable criterion is check_cmap.py's per-character comparison against the font cmap.
Six Pitfalls (All Encountered First-Hand)
| # | Pitfall | Explanation |
|---|---|---|
| 1 | Trailing comments still count characters | "Changing a comment doesn't require re-subsetting" only holds for standalone-line comments. After appending // … hide weight column after two lines of code, the characters hide and weight immediately get reported as missing. Write new comments as standalone lines, or avoid uncommon characters |
| 2 | Chinese in test assertions counts too | Assertion text like ok('… simplified / hit / all') gets counted in the character set. Changing the assertion to avoid out-of-table characters (simplified→current) is more economical than rebuilding the subset for three characters. But UI copy missing characters must be rebuilt, you can't fudge it by swapping words |
| 3 | Importing external table data = changing copy | When populating a detail page with columns of exercise muscle names from an action library table, quadriceps / biceps / hamstrings / rhomboids / medicine ball reported 15 missing characters at once. Keep data files separate; don't modify the main dictionary structure just to display a field |
| 4 | Unbreakable order: merge font PR last | The font subset is a global artifact that depends on all copy. Merge all copy-changing PRs first, then the font PR last. Otherwise, every merge forces a rebuild (real case: fixed 7 characters in font, then a storage PR brought 3 more — wasted a full round) |
| 5 | fonts.js is a generated artifact, don't edit manually | It's a single line of hundreds of thousands of base64 characters; manual editing almost certainly breaks it. To change, re-run the script. To check if you introduced missing characters: git stash -q && <check> ; git stash pop -q; if it's already red before your change, it's a pre-existing issue |
| 6 | Mini programs cannot reference external font files | @font-face src only accepts https:// (whitelisted domains) or base64. For offline use without CDN dependency, you must inline; inline size ≈ woff2 × 4/3 (base64 inflation), so 275 KB woff2 becomes ~367 KB inlined |
How to Choose a Source Font
- Noto Sans SC / Source Han Sans: SIL OFL 1.1, can be used commercially and redistributed (most common choice)
- Variable vs static weights: A variable font (
-VF) contains multiple weights in one file; just point--srcto it; subsetting automatically preserves the axes used - Don't use dubious "free fonts": Fonts with unclear licenses embedded in commercial projects pose real legal risk
- Check if Noto Sans SC is available locally:
python3.12 -c "import os;print(os.path.exists('C:/Windows/Fonts/NotoSansSC-VF.ttf'))"; if not, get it from Google Fonts orgithub.com/notofonts/noto-cjk
Font Size System (Bonus: The Most Common Mistake After Subsetting)
Subsetting only solves "does the character exist", not "is it readable". The right approach when real users report "font is too small":
- Font sizes should come from a single token set (e.g.,
--fs-1 … --fs-8eight levels), never use barefont-size: 26rpxin the page - Chinese body text has a minimum size: on mobile, body text should be no smaller than
32rpx(~16px @375 width), caption text no smaller than24rpx - After increasing font size, always check card title wrapping: increasing by one level often causes "action name + unit" to wrap into two lines, making card height jump
- After adjustments, test on the smallest real screen (e.g., 375×667): looking good on a wide screen doesn't count as looking good
See references/cjk-font-ops.md for the detailed checklist.
Files
scripts/subset_cjk.py— Extract characters + subset + three output modes (file / css / inject)scripts/check_cmap.py— Strict-scope missing character check,exit 1ready for CIscripts/make_test_font.py— Create a minimal TTF with only specified Chinese characters (offline self-test)scripts/selftest.py— End-to-end self-test, 15 assertions, including a counterexample that the checker must actually failreferences/cjk-font-ops.md— Scope details, real incident log, CI integration, font size system
Boundaries
- Only processes Chinese / CJK Unified Ideographs (including Extension A and Compatibility). Japanese Kana and Korean are not covered
- Does not handle font design (weight pairing, line height, letter spacing) — only concerns "does this character exist + volume"
check_cmap.pyidentifies files by extension; dynamically concatenated Chinese (e.g.,'Section' + n + 'Group') can only recognize the literal part — concatenated characters must either be added to the safe character list (except for--no-safety) or have an assertion enumerating possible values