SVG optimizer in pure MoonBit: svgo-compatible plugin pipeline with path data optimization, colour and number cleanup, and render-diff verification
npm i @rivus/svgoimport { optimize } from "@rivus/svgo";
const r = await optimize(svg, { precision: 3 });
r.data; r.originalSize; r.size; r.passes; r.applied;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`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>
),
)
}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$ 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| 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 |
| 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"] |
///|
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\"/>")
}| 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× |
| 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 |
| cases | |
|---|---|
| pass | 289 |
| known differences | 0 |
| skipped | 0 |
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)impl Show for UnknownPluginInstall
Download zipSVG optimizer in pure MoonBit: svgo-compatible plugin pipeline with path data optimization, colour and number cleanup, and render-diff verification