Skip to content
PerfectPanPublic

About

SVG optimizer in MoonBit: svgo's preset-default as a MoonBit library, a 200 KB wasm module and a native CLI

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

Nib, the svgo.mbt mascot: a coral blob drawn as a path, with anchor points for ears and feet

svgo.mbt

Smaller SVGs, 3.6× faster, the same pixels.
svgo's preset-default, written in MoonBit.

Website & playground · API reference · mooncakes.io · npm @rivus/svgo

All 34 plugins in svgo's preset-default, in its order and with its semantics, and none of the Node.js dependency tree: a 188 KB wasm-gc module for the browser, Node.js, Bun and Deno, a CLI that installs with npx (or a native binary), and a MoonBit library. Rendering is checked pixel by pixel against the input: 0 differing pixels on every sample the website shows, and nothing beyond sub-pixel precision effects on the benchmark corpus.

Nib, the mascot above, is a path drawn with its anchor points showing, and a sample too: the copy on the website's first screen carries the metadata a vector editor leaves behind and shrinks from 5,713 B to 2,298 B with the same pixels.

Quickstart

JavaScript (Node 24+, Bun 1.4+, Deno 2, Chrome 130+, Firefox 134+, Safari 18.4+; see Runtime compatibility):

npm i @rivus/svgo
import { optimize } from "@rivus/svgo";
const r = await optimize(svg, { precision: 3 });
r.data; r.originalSize; r.size; r.passes; r.applied;

Command line, without a toolchain (Node 24+; bunx and deno run -A npm:@rivus/svgo work too):

npx @rivus/svgo input.svg -o out.svg
cat input.svg | npx @rivus/svgo > out.svg       # stdin, or pass "-" as the input
npx @rivus/svgo icons -r -o dist                # a directory, recursively
# installed (npm i -g @rivus/svgo) the command is `svgo-mbt`

MoonBit (mooncakes.io library; requires moonc ≥ 0.10.19 — run moon upgrade if moon check reports an undefined Int32 type):

moon add PerfectPan/svgo
///|
test "optimize" {
  let result = @svgo.optimize(
    (
      #|<svg xmlns="http://www.w3.org/2000/svg" width="10px" height="10px">
      #|  <!-- Generator: Sketch -->
      #|  <g fill="#FF0000" stroke="none">
      #|    <rect x="0" y="0" width="10.000" height="10.000"/>
      #|  </g>
      #|</svg>
    ),
  )
  inspect(
    result.data,
    content=(
      #|<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><path fill="red" d="M0 0h10v10H0z"/></svg>
    ),
  )
}

Config provides plugin selection, your own plugins (custom, see Custom plugins), params : Map[String, Json], precision, multipass, and pretty printing; see the API reference for all fields.

Command line

svgo-mbt input.svg                            # optimized SVG on stdout, nothing else
svgo-mbt input.svg -o out.svg                 # write a file, size report on stderr
svgo-mbt input.svg --stats > out.svg          # the report also when the SVG goes to stdout
svgo-mbt input.svg -p 2 --pretty              # 2 decimal places, indented output
svgo-mbt input.svg --json                     # {data, originalSize, size, passes, applied}
svgo-mbt input.svg --plugins convertPathData,sortAttrs
svgo-mbt input.svg --param cleanupIds.preserve=logo,icon --param cleanupIds.minify=false
svgo-mbt input.svg --disable convertShapeToPath --enable moveGroupAttrsToElems
svgo-mbt --list                               # available plugins

Writing files prints a size report on stderr, one row per file as it finishes and a totals line for several (-q silences it, --json replaces it):

$ svgo-mbt icons -r -o dist
  icons/figma-export.svg         570 B →    442 B   −22%
  icons/illustrator-logo.svg    1.1 KB →    528 B   −54%
  icons/inkscape-drawing.svg    2.1 KB →    641 B   −69%
  icons/sketch-icon.svg          836 B →    276 B   −67%
  4 files                       4.6 KB →   1.9 KB   −59%  6.5 ms

For a single file a second line lists the plugins that changed it. A file that fails gets one line, svgo-mbt: icons/bad.svg: unclosed element <g> at offset 8, a failed row in the table and a count in the totals. On a terminal the percentages are green or red; NO_COLOR turns colour off, FORCE_COLOR turns it on for pipes, and stdout is never styled.

Exit codes: 0 on success, 1 for a usage error, 2 when a file could not be read, parsed, optimized or written (the names go to stderr, so a shell loop can act on them).

--param <plugin>.<key>=<value> is repeatable. Values true/false become booleans, integers become numbers, comma-separated values become string arrays, and other values remain strings.

Plugins

Enabled by default, in svgo's preset-default order:

plugin what it does
removeDoctype, removeXMLProcInst, removeComments, removeMetadata strip the prolog and editor comments (<!--! ... --> legal comments are kept)
removeEditorsNSData drop Inkscape / Sketch / Illustrator / Figma namespaces, elements and attributes
cleanupAttrs, removeDesc, cleanupIds, removeUselessDefs normalise whitespace, drop Created with ... descriptions, unused ids and unreferenced <defs> children
cleanupNumericValues round numbers, remove px
convertColors rgb() / names / #RRGGBB to the shortest form
mergeStyles, inlineStyles, minifyStyles merge <style> elements, inline matching rules to style="...", minify CSS and drop unused selectors
removeUnknownsAndDefaults drop attributes equal to their defaults, unless an ancestor overrides them
removeDeprecatedAttrs drop attributes the SVG spec deprecated, keeping the ones that still render
removeNonInheritableGroupAttrs drop presentation attributes off a <g> that children cannot inherit
removeUselessStrokeAndFill drop stroke-* when nothing is stroked, fill-* when nothing is filled
cleanupEnableBackground drop enable-background unless a filter uses BackgroundImage
removeHiddenElems, removeEmptyText zero-size shapes, display:none, empty paths and texts
convertShapeToPath, convertEllipseToCircle rect / line / polyline / polygon to path, equal-radius ellipses to circles
moveElemsAttrsToGroup lift an attribute every child shares onto their group
collapseGroups unwrap groups and push their attributes down
convertPathData element transforms baked into the data, curve runs to arcs, relative/absolute per segment, H/V/S/T shorthands, straight curves to lines, precision with drift compensation
convertTransform multiply, decompose and round transform lists, drop identity and redundant ones
mergePaths join adjacent paths with identical attributes when their outlines do not intersect
removeEmptyAttrs, removeEmptyContainers, removeUnusedNS, sortAttrs, sortDefsChildren final cleanup

Optional: removeDimensions, removeTitle, moveGroupAttrsToElems.

Parameters use svgo's names and JSON shapes. Each plugin receives only its own object; omitted fields use these defaults:

Plugin Parameters and defaults
cleanupIds remove: true, minify: true, preserve: [], preservePrefixes: [], force: false
convertColors currentColor: false, names2hex: true, rgb2hex: true, shorthex: true, shortname: true
convertShapeToPath convertArcs: false, floatPrecision: config precision
convertTransform floatPrecision: config precision (3), transformPrecision: 5 (limited to matrix precision), degPrecision: derived from matrix digits and float precision
removeComments preservePatterns: ["^!"]; false or [] removes all comments
removeUnknownsAndDefaults unknownContent, unknownAttrs, defaultAttrs, uselessOverrides, keepDataAttrs, keepAriaAttrs: all true; keepRoleAttr: false
removeUselessStrokeAndFill stroke: true, fill: true, removeNone: false
sortAttrs xmlnsOrder: "front"; order: ["id", "width", "height", "x", "x1", "x2", "y", "y1", "y2", "cx", "cy", "r", "fill", "stroke", "marker", "d", "points"]

preserve and preservePrefixes accept one string or an array of strings. currentColor accepts a boolean or an exact color string and does not replace colors inside masks. preservePatterns supports literal substring matches and ^-prefixed literal prefix matches, not full regular expressions.

Custom plugins

The MoonBit library runs your own plugins next to the built-in ones. A plugin is a @plugins.Plugin value; pass it in Config::custom. It runs after the named plugins, or at its position when plugins names it (a custom plugin with a built-in's name replaces that built-in). Parameters come from Config::params under the plugin's name, and applied and multipass treat it like any other plugin.

///|
test "custom plugin" {
  let tag_owner : @plugins.Plugin = {
    name: "tagOwner",
    description: "set data-owner on the root element",
    run: (doc, ctx) => {
      guard doc.root() is Some(root) else { return false }
      let owner = ctx.param_string("owner", "design")
      if root.get("data-owner") == Some(owner) {
        return false // unchanged: returning true here would force 10 passes
      }
      root.set("data-owner", owner)
      true
    },
  }
  let r = @svgo.optimize("<svg><!-- c --></svg>", config={
    ..@svgo.Config::default(),
    custom: [tag_owner],
    params: { "tagOwner": { "owner": "icons" } },
  })
  inspect(r.data, content="<svg data-owner=\"icons\"/>")
}

A plugin follows the rules the built-in ones do: it removes or rewrites only what a renderer cannot observe, returns true exactly when it changed the document, and runs on any document in any position without raising. The npm package and the CLI run only the built-in plugins, because JavaScript functions cannot run inside the wasm module; process the SVG string before or after optimize instead.

Performance

Same Node process, both with multipass and the same plugin set (svgo with moveGroupAttrsToElems off, as svgo.mbt runs by default), milliseconds per call (node packages/compare/collect.mjs, Node 24, svgo 4.1.0):

file size svgo.mbt (wasm-gc) svgo-js ratio
sketch-icon.svg 836 B 0.095 0.286 3.0×
inkscape-drawing.svg 2 KB 0.165 0.637 3.9×
SVG_logo.svg 4 KB 0.470 1.695 3.6×
Tux.svg 50 KB 5.679 12.833 2.3×
Ghostscript_Tiger.svg 68 KB 10.096 41.113 4.1×
World map (low resolution) 85 KB 10.605 50.433 4.8×

Between 1.7× and 4.8× depending on the file, 3.6× at the median over the ten files in packages/compare/corpus/ and svgo/testdata/. Cold start on a small icon, whole process (scripts/cli-bench.sh): native CLI about 10 ms, Node build about 50 ms, svgo CLI about 160 ms.

Runtime compatibility

Artifact Runs on Checked by
@rivus/svgo (wasm-gc) Node 24+, Bun 1.4+, Deno 2 (tested with 2.9); Chrome 130+, Firefox 134+, Safari 18.4+ CI runs the 330-case fixture suite through the shipped wasm under Node, Bun and Deno on every push
svgo-mbt CLI, Node build the same runtimes, via npx / bunx / deno run -A same suite plus a CLI smoke test
svgo-mbt native binary linux x86_64, linux arm64, macOS arm64 from GitHub releases; any other platform with moon build --target native --release app/cli built by binaries.yml on each release
PerfectPan/svgo MoonBit library targets wasm-gc, js and native; moonc ≥ 0.10.19 (moon upgrade; CI installs the latest release) moon test on js and native in CI

The wasm needs an engine with WebAssembly GC and JS String Builtins (imported string constants). Older engines fail at instantiate rather than at runtime: Node 22 and 23 report Import module="_", Bun 1.2 reports import wasm:js-string:length must be an object. This cannot be polyfilled from JavaScript because fromCharCodeArray takes a wasm-gc array. The optimizer itself does no I/O; the loader fetches the wasm over http(s) and reads file: URLs through node:fs, which Bun and Deno provide.

Compatibility with svgo

Upstream cases (svgo e4cb29b, 2026-08-27):

cases
pass 289
known differences 0
skipped 0

moveGroupAttrsToElems ships opt-in (--enable moveGroupAttrsToElems). Pushing a group's transform onto its children lets convertPathData bake the matrix into every path, which lengthens coordinates and leaves formerly identical siblings unmergeable. Across the test corpus files it costs 15,859 bytes on the Ghostscript tiger and saves 48 bytes across the rest. svgo shows the same effect on that file (68,101 bytes with the plugin, 52,029 without, against 52,690 for svgo.mbt).

svgo also has 19 opt-in plugins; removeDimensions and removeTitle are implemented, and the other 17 are not.

Verification

CI installs the current official MoonBit release on Linux and macOS and records moon version --all in the job log and run summary. It checks and builds the supported backends, runs the JS/native tests, exercises the native and JS CLIs, and builds the website. The wasm-gc library imports Math, Number and String from its JavaScript host, so its tests run through the shipped npm loader under Node, Bun and Deno; standalone moonrun does not supply those imports.

moon version --all          # record the toolchain used for compatibility checks
scripts/verify.sh            # check, fmt, .mbti drift, fixtures, tests on js / native
scripts/verify.sh --full     # + wasm build, sizes vs svgo-js, resvg pixel diff, speed (needs pnpm install)

Runs unit tests, svgo's own fixture suite, resvg pixel diff, and byte-for-byte corpus checks. Details and developer guides: docs/ARCHITECTURE.md, CONTRIBUTING.md, AGENTS.md.

License

MIT. Plugin semantics follow svgo (MIT, © Kir Belevich and contributors); svgo's license and the notices for the ported code and fixtures are in THIRD_PARTY_NOTICES.md.

About

SVG optimizer in MoonBit: svgo's preset-default as a MoonBit library, a 200 KB wasm module and a native CLI

Topics

Resources

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages