Last active
May 25, 2020 12:17
-
-
Save syuji-higa/89ddd8ca8f28cbb1aee8120fed85e2eb to your computer and use it in GitHub Desktop.
Node.js - minify image
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const glob = require('glob') | |
const mkdirp = require('mkdirp') | |
const imagemin = require('imagemin') | |
const pngquant = require('imagemin-pngquant') | |
const mozjpeg = require('imagemin-mozjpeg') | |
const gifsicle = require('imagemin-gifsicle') | |
const svgo = require('imagemin-svgo') | |
const { | |
readFile, | |
writeFile | |
} = require('fs') | |
const { | |
dirname, | |
extname, | |
join, | |
relative | |
} = require('path') | |
const plugins = { | |
png: pngquant({ | |
quality: [0.8, 0.9], // 0 ~ 1 | |
speed: 1 | |
}), | |
jpg: mozjpeg({ | |
quality: 80 // 0 ~ 100 | |
}), | |
gif: gifsicle({ | |
optimizationLevel: 3 // 1 ~ 3 | |
}), | |
svg: svgo({ | |
plugins: [{removeViewBox: false}] | |
}) | |
} | |
glob('src/**/*.+(png|jpg|gif|svg)', (err, files) => { | |
if (err) { | |
console.log(err) | |
return | |
} | |
for (const file of files) { | |
readFile(file, 'base64', (err, img) => { | |
if (err) { | |
console.log(err) | |
return | |
} | |
if (!img) { | |
return | |
} | |
(async () => { | |
const _ext = extname(file).replace('.', '') | |
const _buf = await imagemin | |
.buffer(Buffer.from(img, 'base64'), { | |
plugins: [ | |
plugins[_ext], | |
], | |
}) | |
.catch((err) => { | |
console.log(err) | |
return | |
}) | |
const _dest = join('./dest', relative('./src', file)) | |
await mkdirp(dirname(_dest)).catch((err) => { | |
if (err) { | |
console.log(err) | |
return | |
} | |
}) | |
writeFile(_dest, _buf, (err) => { | |
if (err) { | |
console.log(err) | |
return | |
} | |
}) | |
console.log(`finish: ${ file }`) | |
})() | |
}) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment