.   .   .
We're always looking for great talent‼️ 🚀😄 And we're passionate about driving innovation and improving lives. Join us as we help social impact organizations and enterprise customers build their web apps. Apply today!
.   .   .

Optimized images are good for everyone. There’s no good reason not to want to do it. They’re great for fast browsing and great for SEO. The problem is that they’re really freaking easy to forget.

So I asked myself. How could I automatically optimize all images before each git commit?

Here’s what I came up with

Firstly, I’ll assume your project is set up and running with git.

Next, even if you aren’t working on a javascript project, go ahead and add a package.json. It will allow us to use some tools that will be really helpful here. You can do so by installing node and yarn if you haven’t already done so and then running the following:

yarn init

Now we need a package that will automatically insert a script prior to completing a git commit. We found husky. Add that to your project with the following:

yarn add husky

Now, we could run a script that optimized images automatically for the whole project but that would be wasteful. So we want a way to only optimized staged files that you are about to commit. We found lint-staged. It works perfectly for this. Go ahead and add that to your project with

yarn add lint-staged

OK, so now we have all of the groundwork needed but how will we actually optimize the images. I choose pngquant and jpegoptim. On a Mac, you can install them with homebrew by doing the following

brew install pngquant
brew install jpegoptim

That will be a requirement for your project though so make sure you add something to the README that informs other contributors that their machine will need those packages. Their commits will fail otherwise.

We’re officially ready to add the final touches. Update your package.json file so it contains something like this:

"scripts": {
    "precommit": "lint-staged"
"lint-staged": {
    "*.{png,PNG}": [
        "pngquant --quality=70-85 --force --ext=.png --",
        "git add --"
    "*.{jpg,jpeg,JPG,JPEG}": [
        "jpegoptim --strip-all -m85 --",
        "git add --"

The code should be self explanatory. Read through the manuals on jpegoptim and pngquant for further details. One thing you’ll notice is that I added a git add after each command. Prior to adding that, the commit was taking place before the compression. That addition seemed to fix the issue.

Finally, give it a whirl. Add some images to your project and try to commit them. You should see that they are automatically optimized prior to committing.

.   .   .

We're Hiring‼️ ?? Looking to join our team of web developers? We're passionate about innovation, family, and community. Apply today!