Skip to content

Instantly share code, notes, and snippets.

@parkerziegler
Created September 7, 2020 02:19
Show Gist options
  • Save parkerziegler/9054d610326fb7db124a4456b27e6244 to your computer and use it in GitHub Desktop.
Save parkerziegler/9054d610326fb7db124a4456b27e6244 to your computer and use it in GitHub Desktop.
A simple Node.js script to generates assets for srcSet from a base asset using sharp.
const sharp = require('sharp');
const fs = require('fs');
const path = require('path');
// Set your sizes array based on the needs of your application.
const sizes = [
{ width: 480, suffix: 'sm' },
{ width: 800, suffix: 'md' },
{ width: 1080, suffix: 'lg' },
{ width: 1280, suffix: 'xl' },
{ width: 1600, suffix: 'xxl' }
];
function generateSrcSet(dir) {
fs.readdirSync(dir).forEach((file) => {
const basename = path.basename(file);
const ext = path.extname(file);
const filePath = `${dir}/${file}`;
Promise.all(
sizes.map(({ width, suffix }) => (
sharp(filePath).resize(width).toFile(`${dir}/${basename}-${suffix}.${ext}`)
))
).then(() => {
console.log('Image resize succeeded!');
}).catch((err) => {
console.error(`Image resize failed with error: ${err}`);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment