Skip to content

Instantly share code, notes, and snippets.

@jerolan
Last active April 27, 2021 15:23
Show Gist options
  • Select an option

  • Save jerolan/8607213be460f9723ef184bcdd8a5892 to your computer and use it in GitHub Desktop.

Select an option

Save jerolan/8607213be460f9723ef184bcdd8a5892 to your computer and use it in GitHub Desktop.
sharpImageOptim.js
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