1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

完全クライアントサイドで動く SVG 最適化ツールを作った

1
Posted at

作ったもの

SVG Optimizerhttps://sen.ltd/portfolio/svg-optimizer/

スクリーンショット

  • 12 種類の変換(トグル可能)
  • 元と最適化後を並べて表示 + プレビュー
  • リアルタイムサイズ統計
  • ダウンロード / コピー / ドロップゾーン
  • 完全ローカル処理(アップロードなし)

vanilla JS、ゼロ依存、ビルド不要node --test で 52 ケース。

regex ベースの変換

全変換が string → string の純関数。DOMParser も AST も使わない。SVG 最適化で必要な操作は正規表現で十分。

数値の丸め

Figma などが吐く M 12.3456789,45.6789012 ... のような余計な小数を丸める:

return svg.replace(/-?\d+\.\d+/g, (match) => {
  const n = Math.round(parseFloat(match) * 100) / 100;
  return n.toString();
});

小数部のある数値だけにマッチするので、整数は触らない。

デフォルト属性の削除

opacity="1", stroke-width="1" など、デフォルト値と同じ属性は消しても意味が変わらない。

エディタアーティファクト

Sketch / Figma / Inkscape が残すエディタ特有の id・属性・名前空間を除去。xmlns="http://www.w3.org/2000/svg" だけは絶対に消さない(SVG の必須宣言)。

サイズ計算は TextEncoder

const originalBytes = new TextEncoder().encode(original).length;

string.length は UTF-16 コード単位の数。実ファイルサイズ(UTF-8 バイト数)とは違うので、正確なサイズには TextEncoder が必須。

シリーズ

100+ 公開ポートフォリオ シリーズの #60 です。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?