356 文字
2 分
コミット前に画像を圧縮させる
画像を圧縮するスクリプト
画像を圧縮するライブラリに今回はsharpを利用した。
本当は WebP などに変換した方が圧縮効率は遥かに高いが、Markdown に画像を埋め込んでおりパスを書き換えさせるスクリプトも作るのが面倒だったので、今回は 1200x1200px 以内に画像をリサイズするだけに留めている。
import { readFile } from "node:fs/promises";import sharp from "sharp";
const minifyFile = async (filename) => { try { const sourceData = await readFile(filename); const info = await sharp(sourceData) .resize({ width: 1200, height: 1200, fit: sharp.fit.inside, // このオプションをtrueにすると、元画像よりも小さい場合はリサイズしない withoutEnlargement: true, }) .toFile(filename);
console.log({ filename: filename, beforeSize: sourceData.length, afterSize: info.size, }); } catch (error) { throw error; }};
try { const files = process.argv.slice(2); const promises = files.map(minifyFile); await Promise.all(promises);} catch (error) { console.log(error); process.exit(1);}
Lefthook でコミット前に画像を圧縮させる
Lefthookは Git フックを管理するツールで、コミットなどをトリガーに特定のスクリプトを実行させることができる。
同種のツールとしては Husky + Lint Staged がある。個人的には Node.js 以外の環境でも導入しやすく、比較的エッジケースの少ないと思われる Lefthook の方を好んで利用している。
lefthook.yml
で次のような設定を行い、コミット前に画像を圧縮させるようにした。
pre-commit: parallel: true commands: compress-images: tags: frontend glob: "*.{png,jpg,jpeg,webp}" run: node ./scripts/compress-image.js {staged_files} && git add {staged_files}
コミット前に画像を圧縮させる
https://blog.ohirunewani.com/posts/compress-image-by-commit/