svg-font-maker
v0.1.0
Published
Deterministic SVG-to-icon-font builder with a permanent codepoint ledger
Maintainers
Readme
svg-font-maker
Compile a directory of SVGs into an icon font — deterministically, with a codepoint ledger that is never reassigned.
Why
Most of this is glue. Two things underneath it are the reason the package exists, because they are the two things icon-font setups get wrong:
Deterministic glyph order. Glyph IDs follow the order glyphs are written to the font stream. Wrappers that scan a directory hand that order to fs.readdirSync, and ext4 hashes filenames with a per-volume random seed — so the same SVGs produce different font bytes on CI than on your machine. If you byte-compare the committed font (and you should), the build fails with no source change and rebuilding locally just reproduces your own order. This package feeds the stream an explicitly sorted list and tests the property directly.
A permanent codepoint ledger. Delete an icon and a naive builder recycles its codepoint for the next one. Every browser and CDN edge holding the old font then renders the wrong icon — not a missing box, the wrong glyph. Ledger entries here are append-only: a removed icon keeps its entry forever, reported as reserved.
Everything else — SVG validation, geometry canonicalization, the drift gate, the preview — falls out of those two.
Prerequisites
- Install Bun — used to build the package
- Node.js 20+ to run the CLI
Install
bun add -d svg-font-makerUsage
Create svg-font-maker.config.mjs. It is declarative — paths and options, no code:
export default {
svgDir: "icons",
ledger: "icons/codepoints.json",
preview: ".tmp/preview.html",
font: { name: "myicons", classPrefix: "icon-" },
output: {
woff2: "public/myicons.woff2",
css: "src/icons.css",
types: "src/icon-name.ts",
},
};That is a complete config. It writes the font, a stylesheet with @font-face plus one rule per icon, and a TypeScript union of the names — each written in build mode and byte-compared in check mode.
Tune any of the three by passing an object instead of a path:
output: {
woff2: "src/assets/fonts/myicons.woff2",
css: {
path: "src/styles/_icons.generated.scss",
// Out-specify a component library that styles its own icon element,
// instead of reaching for !important.
extraSelectors: [".ui-icon[class*=' icon-']"],
// Override when your bundler rewrites asset urls differently.
fontUrl: "../assets/fonts/myicons.woff2",
cacheBust: true, // append ?<hash> — default
pseudo: "before", // default
},
types: {
path: "src/app/icon-name.ts",
constName: "ICON_NAMES", // default: <FONT_NAME>_NAMES
typeName: "IIconName", // default: I<FontName>Name
emit: "const", // or "union" to ship nothing to the bundle
prettier: true, // format with this project's prettier config
},
}# validate, compile, write every artifact
svg-font-maker build
# same computation, read-only: fails if a committed artifact is stale (use in CI)
svg-font-maker checkAdding an icon
- Export a monochrome SVG. If it has a stroke, outline it first (Figma: Object → Outline Stroke) — the font format has no stroke concept.
- Save it as
<svgDir>/<name>.svgin snake_case. - Run
svg-font-maker build. - Open the preview and check the new glyph next to the others at 16/24/32px.
You do not need to fit or center the SVG by hand. Any file that is not already viewBox="0 0 <w> <emSize>" anchored at the origin is treated as new and canonicalized: ink scaled to fill the em-square on its longest axis, centered on the other, flushed to x=0. A file that already looks canonical is never rewritten; if it is a new icon, the build warns when its ink does not actually fill the em-square or when its viewBox is too wide.
Removing an icon
Delete the SVG and rebuild. Its class and its entry in every artifact disappear, but its ledger entry is kept forever — printed as a reserved warning — so the codepoint can never be handed to a future icon.
Config
| Option | Required | Description |
| ------------------------ | -------- | ------------------------------------------------------------------------------------------------- |
| svgDir | ✅ | Directory holding one SVG per icon |
| ledger | ✅ | Path to the permanent name -> codepoint JSON map |
| output.woff2 | — | Where to write the compiled font |
| output.css | — | Stylesheet path, or a CssOutput object (see above) |
| output.types | — | TypeScript path, or a TypesOutput object (see above) |
| root | — | Base directory reported paths are relative to (default process.cwd()) |
| font.name | — | font-family name (default icons) |
| font.classPrefix | — | Prefix for generated class names (default icon-) |
| font.emSize | — | Units per em (default 1024) — see Never change these |
| font.baselinePercent | — | Baseline offset as a percentage of emSize, deriving the descent (default 6.25) |
| codepoints.start | — | Where new codepoints begin (default 0xe000) — raise it to reserve room below for a migrated set |
| naming.pattern | — | Allowed icon names (default ^[a-z0-9]+([_-][a-z0-9]+)*$) |
| naming.hyphenAllowlist | — | Names allowed to keep a hyphen, for grandfathered icons |
| requireImportIn | — | { file, contains } — assert a file still references the generated stylesheet |
| hardcodedEscapes | — | { dir } — scan for hand-written \eXXX escapes and assert each still resolves |
| banner | — | Do-not-edit comment for generated text files; defaults to one naming svgDir; false to omit |
| preview | — | Where to write the old-vs-new HTML glyph preview |
| tmpDir | — | Scratch directory for intermediate font files (default .svg-font-maker) |
| artifacts | — | Escape hatch: extra { path, generate } outputs the built-ins cannot express |
| guards | — | Escape hatch: (context) => string[] for invariants the built-in checks cannot express |
| shippedCodes | — | Escape hatch: overrides where the immutability check reads previous codepoints from |
Two checks worth switching on
requireImportIn. If the import of the generated stylesheet is dropped or reordered away, every icon disappears from the app while every artifact stays perfectly in sync — so the drift gate alone reports success. One line closes it:
requireImportIn: { file: "src/styles/_fonts.scss", contains: "./icons.generated" },hardcodedEscapes. A content: '\e01e' written by hand somewhere is invisible to the artifact comparison, so a moved codepoint would render the wrong glyph there with a green build:
hardcodedEscapes: { dir: "src", extensions: [".scss"] },The generated stylesheet is excluded automatically.
The ledger-immutability check needs no configuration: the package wrote your stylesheet, so it reads the previously shipped codepoints back out of it by itself. shippedCodes only exists for when a custom artifact produces the stylesheet instead.
Programmatic API
runIconFont(config, "build" | "check") is what the CLI calls. It resolves with an Outcome (shipped, hash, glyphCount, newIcons, reserved, canonicalized, warnings, written) or throws IconFontError, whose messages array holds one already-phrased line per problem.
import { runIconFont, IconFontError, type IconFontConfig } from "svg-font-maker";The surface is deliberately small: the entry point, the config types (IconFontConfig, Output, CssOutput, TypesOutput, ImportRequirement, Artifact, Guard), the types reachable from the two escape hatches (BuildContext, GuardContext, ShippedIcon, Ledger, NewIcon, ResolvedConfig, ResolvedOutput), the defaults worth overriding against (DEFAULT_NAME_PATTERN, PUA_START, PUA_END), and parseCssCodepoints. Internals are not exported — every export is a compatibility promise, and a narrow surface is what lets the inside change without a major version.
BuildContext.shipped is { name, className, code }[] in ledger order. That single projection is what every artifact is generated from, so a custom generate never has to touch the ledger or re-apply the class prefix.
Never change these
font.name— every existing CSS reference and font registration points at it.font.emSizeandfont.baselinePercent— pick once, per project, and never touch them again. They reflow the baseline and size of every existing glyph, not just new ones.codepoints.start— lowering it after the first build lets a new icon land on a code an old one already used.- The font toolchain versions —
svgicons2svgfont,svg2ttf,ttf2woff2,svgoandsvg-pathdataare pinned exactly, with no caret, and those pins are load-bearing. A patch bump anywhere in that chain changes the emitted bytes,checkreports every committed artifact as stale, and a routine dependency refresh silently ships a new font binary. Changing any of them is a major version of this package.
Local Development
# Build (bundle + .d.ts)
bun run build
# Type check
bun run typecheck
# Lint
bun run lint
# Lint and auto-fix
bun run lint:fix
# Format
bun run format
# Run tests (watch mode)
bun run test
# Run tests once
bun run test:run
# Lint + format + tests in one command
bun run check
# Link for local testing
bun link
svg-font-maker --helpNotes
- The
buildscript bundles ESM intodist/via Bun with dependencies left external, then emits.d.tswithtsc. Thebinfield points todist/cli.js. - The
preparescript runs the build automatically on install when publishing. - Run the CLI under Node, not Bun:
ttf2woff2falls back to an Emscripten build that does not terminate cleanly under Bun's runtime. - Linting is handled by oxlint, formatting by oxfmt.
- Tests are written with Vitest and live next to the code in
src/*.test.ts. - A Husky
pre-commithook runsbun run checkbefore every commit.
License
MIT
