Skip to content

Instantly share code, notes, and snippets.

@tomchentw
Last active March 2, 2022 07:42
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tomchentw/19c4275bc2c2e89e18a616355a3cca88 to your computer and use it in GitHub Desktop.
Save tomchentw/19c4275bc2c2e89e18a616355a3cca88 to your computer and use it in GitHub Desktop.
Auto compress images with husky, lint-staged and imagemin

The flow

husky (setup git commit hooks) -> lint-stages (run specific commands by file type) -> imagemin (minify files)

git add -A
git commit # It will compress your images into git repo now

Since the images is now fully compressed, no extra steps is required by webpack/browserify……whatever.

'use strict';
const fs = require('fs');
const imagemin = require('imagemin');
const plugins = [
['imagemin-gifsicle', {
interlaced: true,
}],
['imagemin-jpegtran', {
progressive: true,
}],
['imagemin-optipng', {
optimizationLevel: 5,
}],
['imagemin-svgo', {
plugins: [
{removeViewBox: false},
],
}],
].map(it => require(it[0])(it[1]))
const minifyFile = filename =>
new Promise((resolve, reject) =>
fs.readFile(filename, (err, data) => err ? reject(err) : resolve(data))
)
.then(originalBuffer => imagemin
.buffer(originalBuffer, { plugins })
.then(minimizedBuffer => ({
// minimized: minimizedBuffer !== originalBuffer,
// originalSize: originalBuffer.length,
minimizedBuffer,
}))
).then(({ minimizedBuffer }) => new Promise((resolve, reject) =>
fs.writeFile(filename, minimizedBuffer, err => err ? reject(err) : resolve())
))
Promise.resolve(process.argv)
.then(x => x.slice(2))
.then(x => x.map(minifyFile))
.then(x => Promise.all(x))
.catch(e => {
console.error(e)
process.exit(1)
})
{
"scripts": {
"precommit": "lint-staged"
},
"lint-staged": {
"*.{png,jpeg,jpg,gif,svg}": [
"node ./imagemin.js",
"git add"
]
},
"devDependencies": {
"husky": "^0.14.3",
"imagemin": "^5.3.1",
"imagemin-gifsicle": "^5.2.0",
"imagemin-jpegtran": "^5.0.2",
"imagemin-optipng": "^5.2.1",
"imagemin-pngquant": "^5.0.1",
"imagemin-svgo": "^5.2.2",
"imports-loader": "^0.7.1",
"lint-staged": "^4.0.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment