|
| 1 | +import fs from 'fs' |
| 2 | +import find from 'find' |
| 3 | +import filesize from 'filesize' |
| 4 | +import imagemin from 'imagemin' |
| 5 | +import imageminGifsicle from 'imagemin-gifsicle' |
| 6 | +import imageminJpegtran from 'imagemin-jpegtran' |
| 7 | +import imageminOptipng from 'imagemin-optipng' |
| 8 | +import imageminSvgo from 'imagemin-svgo' |
| 9 | +import parseFilepath from 'parse-filepath' |
| 10 | +import chalk from 'chalk' |
| 11 | + |
| 12 | +const plugins = [ |
| 13 | + imageminGifsicle({}), |
| 14 | + imageminJpegtran({}), |
| 15 | + imageminOptipng({}), |
| 16 | + imageminSvgo({}) |
| 17 | +] |
| 18 | + |
| 19 | +let savedSize = 0 |
| 20 | + |
| 21 | +const run = async () => { |
| 22 | + const regex = new RegExp(/\.gif|\.jpeg|\.jpg|\.png$/) |
| 23 | + |
| 24 | + const files = find.fileSync(regex, 'icons/'); |
| 25 | + |
| 26 | + for (const file of files) { |
| 27 | + await optimized(file) |
| 28 | + } |
| 29 | + |
| 30 | + if (savedSize > 0) { |
| 31 | + console.info(`\n🎉 You saved ${readableSize(savedSize)}.`) |
| 32 | + } else { |
| 33 | + console.info(`\n🎉 Nothing to optimize.`) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +const size = (filename) => { |
| 38 | + return fs.statSync(filename).size |
| 39 | +} |
| 40 | + |
| 41 | +const readableSize = (size) => { |
| 42 | + return filesize(size, { round: 5 }) |
| 43 | +} |
| 44 | + |
| 45 | +const optimized = async (filename) => { |
| 46 | + let output = parseFilepath(filename).dir || './' |
| 47 | + |
| 48 | + const fileSizeBefore = size(filename) |
| 49 | + |
| 50 | + if (fileSizeBefore === 0){ |
| 51 | + console.info(chalk.blue(`Skipping ${filename}, it has ${readableSize(fileSizeBefore)}`)) |
| 52 | + return |
| 53 | + } |
| 54 | + |
| 55 | + const pluginsOptions = { |
| 56 | + destination: output, |
| 57 | + plugins |
| 58 | + } |
| 59 | + |
| 60 | + const filenameBackup = `${filename}.bak` |
| 61 | + fs.copyFileSync(filename, filenameBackup) |
| 62 | + |
| 63 | + try { |
| 64 | + await imagemin([filename], pluginsOptions) |
| 65 | + |
| 66 | + const fileSizeAfter = size(filename) |
| 67 | + const fileSizeDiff = fileSizeBefore - fileSizeAfter |
| 68 | + if (fileSizeDiff > 0){ |
| 69 | + savedSize += fileSizeDiff |
| 70 | + console.info(chalk.green(`Optimized ${filename}: ${chalk.yellow(readableSize(fileSizeAfter))}`)) |
| 71 | + } else { // file after same or bigger |
| 72 | + // restore previous file |
| 73 | + fs.renameSync(filenameBackup, filename) |
| 74 | + |
| 75 | + console.info(`${filename} ${chalk.red(`already optimized`)}`) |
| 76 | + } |
| 77 | + |
| 78 | + } catch (err) { |
| 79 | + console.info(chalk.red(`Skip ${filename} due to error when optimizing`)); |
| 80 | + } |
| 81 | + |
| 82 | + // delete backup file |
| 83 | + if (fs.existsSync(filenameBackup)) { |
| 84 | + fs.unlinkSync(filenameBackup) |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +(async () => { |
| 89 | + await run(); |
| 90 | +})(); |
0 commit comments