Last active
June 30, 2020 09:01
-
-
Save kellymears/066bfa98433eaa19093daefd4766c3a9 to your computer and use it in GitHub Desktop.
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 chalk = require('chalk') | |
const fs = require('fs-extra') | |
const sharp = require('sharp') | |
const globby = require('globby') | |
/** | |
* Where to get dem piccies. | |
*/ | |
const SITE_PATHS = [ | |
`web/app/uploads/**/*.jpg`, | |
`web/app/uploads/**/*.jpeg`, | |
`web/app/uploads/**/*.png`, | |
`web/app/themes/sage/resources/assets/images/*.jpg`, | |
`web/app/themes/sage/resources/assets/images/*.jpeg`, | |
`web/app/themes/sage/resources/assets/images/*.png`, | |
] | |
/** | |
* Image options | |
*/ | |
const options = { | |
png: { | |
progressive: true, | |
quality: 50, | |
compressionLevel: 6, | |
}, | |
jpeg: { | |
progressive: true, | |
quality: 50, | |
optimizeScans: true, | |
}, | |
} | |
/** | |
* Match file extensions | |
* to sharp callables | |
*/ | |
const EXTS = { | |
jpg: 'jpeg', | |
jpeg: 'jpeg', | |
png: 'png', | |
} | |
/** | |
* Process images | |
*/ | |
globby.sync(SITE_PATHS).map(async image => { | |
let hasErr | |
const tmp = image.replace('web/', 'tmp/') | |
const ext = EXTS[image.split('.')[image.split('.').length-1]] | |
const opt = options[`${ext}`] | |
/** | |
* Copy to tmp | |
*/ | |
try { | |
console.log(`Copying to: ${chalk.cyan(tmp)}`) | |
await fs.copy(image, tmp) | |
} catch (e) { | |
hasErr = true | |
console.error(chalk.red(e)) | |
} | |
/** | |
* Process image | |
*/ | |
if (!hasErr) { | |
try { | |
await sharp(tmp)[`${ext}`](opt).toFile(image) | |
console.log(`Image processed: ${chalk.green(image)}`) | |
} catch (e) { | |
hasErr = true | |
console.error(chalk.red(e)) | |
} | |
} | |
/** | |
* Remove tmp | |
*/ | |
if (!hasErr) { | |
try { | |
await fs.remove(tmp) | |
} catch (e) { | |
hasErr = true | |
console.error(chalk.red(e)) | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment