DEV Community

Cover image for A git pre-commit hook that optimises images with sharp
Sahadat Husain
Sahadat Husain

Posted on

A git pre-commit hook that optimises images with sharp

A pre-commit hook can re-encode staged images before they enter history. In a test repo, a 9,804,300 byte camera JPEG was committed as 173,455 bytes, and a 576,828 byte JPEG as 307,960. The hook is a short sharp script. The trap is running it twice on the same file.

Why optimise at commit time?

Git keeps every version of a binary forever. A 9.8 MB photo you delete next week stays in every clone. Fixing it after the commit means rewriting history. Fixing it at commit time costs nothing, because the big file never enters the repo.

What does the hook do?

A hook is any executable named .git/hooks/pre-commit. Ours is two lines that call a Node script:

#!/bin/sh
node scripts/optimise-staged.mjs
Enter fullscreen mode Exit fullscreen mode

The script asks git for staged files, re-encodes each JPEG, PNG and WebP, writes the result over the file, and stages it again. It keeps the new file only if it saves at least 5%.

// optimise-staged.mjs: re-encode staged JPEG/PNG/WebP files in place, keep the result only if it saves at least 5%.
import { execFileSync } from 'node:child_process';
import { readFile, writeFile } from 'node:fs/promises';
import { extname } from 'node:path';
import sharp from 'sharp';

const staged = execFileSync('git', ['diff', '--cached', '--name-only', '--diff-filter=ACM', '-z'], { encoding: 'utf8' })
  .split('\0')
  .filter((f) => /\.(jpe?g|png|webp)$/i.test(f));

const MAX_WIDTH = 2000;
const MIN_GAIN = 0.95; // keep a re-encode only if it saves at least 5%
let before = 0, after = 0;
for (const file of staged) {
  const input = await readFile(file);
  let img = sharp(input).rotate().resize({ width: MAX_WIDTH, withoutEnlargement: true });
  const ext = extname(file).toLowerCase();
  if (ext === '.png') img = img.png({ compressionLevel: 9, effort: 10 });
  else if (ext === '.webp') img = img.webp({ quality: 80 });
  else img = img.jpeg({ quality: 82, mozjpeg: true });
  const output = await img.toBuffer();
  before += input.length;
  if (output.length < input.length * MIN_GAIN) {
    await writeFile(file, output);
    execFileSync('git', ['add', '--', file]);
    after += output.length;
    console.log(`optimised ${file}: ${input.length} -> ${output.length} bytes`);
  } else {
    after += input.length;
    console.log(`kept      ${file}: ${input.length} bytes (re-encode was ${output.length})`);
  }
}
if (staged.length) console.log(`${staged.length} images, ${before} -> ${after} bytes`);
Enter fullscreen mode Exit fullscreen mode

Three choices worth knowing. --diff-filter=ACM skips deleted files. -z keeps filenames with spaces intact. .rotate() with no argument applies the EXIF orientation, so the pixels stay upright when sharp drops the metadata.

What happened on a real commit?

We made a scratch repo and staged four real files from this site's image folder. This is what git printed:

optimised images/camera.jpeg: 9804300 -> 173455 bytes
optimised images/photo.jpg: 576828 -> 307960 bytes
optimised images/result.png: 337398 -> 337397 bytes
optimised images/small.webp: 51500 -> 51042 bytes
4 images, 10770026 -> 869854 bytes
Enter fullscreen mode Exit fullscreen mode

(That run used the first version of the script, which kept any smaller result. The 5% guard came after the next section.)

Staged against committed bytes for camera.jpeg and photo.jpg

The camera photo went from 4964 × 2782 to 2000 × 1121 and from 9,804,300 to 173,455 bytes. Most of that saving is the resize, not the quality setting. The PNG saved 1 byte and the WebP 458 bytes: they were already small, so re-encoding them was noise.

What is the trap?

Lossy re-encoding loses a little each time. We copied the already optimised photo.jpg and committed it again:

optimised images/photo-copy.jpg: 307960 -> 305445 bytes
Enter fullscreen mode Exit fullscreen mode

Another round gave 305,445 to 304,685. Each pass saves under 1% and costs a little quality. Run a hook on every commit and an image touched ten times is re-encoded ten times.

The 5% guard fixes it. With MIN_GAIN = 0.95, the next copy printed:

kept      images/photo-copy3.jpg: 304685 bytes (re-encode was 304350)
Enter fullscreen mode Exit fullscreen mode

A new, unoptimised 176,505 byte photo still shrank to 95,105 bytes with the guard on. A guard like this separates files that needed work from files that did not.

Note: The hook rewrites the file in your working tree and stages the result. If you staged only part of a file with git add -p, the hook stages all of it. Skip the hook for one commit with git commit --no-verify.

What should you change before using it?

  • Share the hook. .git/hooks is not versioned. Use a tool such as Husky, or set core.hooksPath to a folder in the repo.
  • Pick your own quality and width. 82 and 2,000 pixels are our test values, not advice for your site.
  • Pair it with a CI check. A hook can be skipped. A byte budget in CI cannot. See our article on failing CI over image bytes.

For the format question behind the quality number, our comparison of AVIF, WebP and JPEG has the byte differences.

How I measured

  • Date: 2026-10-18. Machine: Apple M1 Pro, macOS 15.7.3.
  • Node 24.22.0, sharp 0.35.4, libvips 8.18.6.
  • KB = 1,000 bytes. Raw numbers are in measured.json next to this article.
  • A scratch git repo (git 2.39.5) with four copies of site images; the hook ran on a normal git commit. The project repo was not touched.

What I did not test

I did not compare image quality before and after, only bytes. I did not test Husky, Windows, or a staged partial file.


I build Blinkimg, an image compressor and converter with a developer API. I wrote this article with help from an AI assistant (Claude), which ran the code on my machine; every number in it comes from those runs.

Top comments (0)