Tool Design: The Operating Principle of cn-font-split
cn-font-split is a font packaging plugin for the Chinese web character plan that can run in Node.js, Deno, and browsers, helping developers package font files.
The Operating Environment of cn-font-split
The source code of cn-font-split is written in TypeScript, and it uses npm to link to C++ code-based WASM functionality. Thanks to the powerful performance and cross-platform characteristics of WebAssembly, cn-font-split can be run directly in the browser.
The Process of Packaging Font Files
The process of packaging font files in cn-font-split is mainly divided into the following steps. This part of the code is centralized here.
- Read the binary font file
- The main types of font files are mainstream OTF or TTF font files. Other types of fonts will be converted to OTF for processing.
- Parse basic font information
- This includes the font's name, size, licensing information, and more.
- Generate SVG files
- The font stores glyph point information, allowing for vector descriptions.
- SVG is more space-efficient and performs better than PNG.
- Collect feature relationships
- Collect the encoding information of glyphs in the font and the mapping relationship of glyph features.
- This step mainly supports font feature requirements.
- Pre-subset
- Prioritize the forced subsetting collection selected by the user.
- Obtain all Unicode character sets within the package.
- Exclude the forced subsetting collection.
- Perform interval subsetting, such as processing the Latin character set and the Chinese character set separately at this stage.
- Use uniform sampling to estimate the initial size of the subsets.
- Limit the maximum number of characters per package to prevent extreme values.
- Obtain the initial subsetting results.
- Clean up small value fragments from the initial subsetting results to ensure each package size is appropriate.
- OTF subsetting construction
- Construct the subset based on the pre-subsetting information.
- The font subset built after completion is of OTF binary type.
- This step completes the subsetting; the following parts focus on optimization.
- WOFF2 Compression
- Send the OTF binary to WOFF2 compression threads via a multi-threaded mode for format conversion.
- The speed increase brought by multi-threading is very noticeable but requires multiple CPUs.
- The Node.js and Bun environments use native dependencies, significantly speeding up beyond the WASM version.
- The Deno and browser versions use the WASM version for the compression core, offering stronger compatibility.
- Collect all process information during the packaging process, generating CSS files, report files, and other information.