Last active
April 27, 2021 15:23
-
-
Save jerolan/8607213be460f9723ef184bcdd8a5892 to your computer and use it in GitHub Desktop.
sharpImageOptim.js
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 sharp = require('sharp'); | |
| const fs = require('fs'); | |
| const directory = './public'; | |
| const extensions = ['jpeg', 'jpg', 'png', 'webp', 'avif', 'gif', 'svg', 'tiff']; | |
| const breakpoints = [640, 768, 1024, 1280, 1536]; | |
| fs.readdirSync(directory) | |
| .filter(filterImagePath) | |
| .forEach((dir) => { | |
| // Create an image per existing breakpoint in parallel | |
| Promise.all(breakpoints.map((width) => createSharp(dir, width))); | |
| }); | |
| function getPathExt(dir) { | |
| const split = dir.split('.'); | |
| return split[split.length - 1].toLowerCase(); | |
| } | |
| function filterImagePath(dir) { | |
| const ext = getPathExt(dir); | |
| return extensions.includes(ext); | |
| } | |
| function createSharp(dir, width) { | |
| const ext = getPathExt(dir); | |
| sharp(`${directory}/${dir}`) | |
| .resize(width) | |
| .toFile(`${directory}/${dir}-${width}.${ext}`); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment