Slipshade's avatar

Sharp image folder compression and convertion

How to configure Sharp so that all jpg & png files in 'src/images' folder convert to webp & avif in the same folder, replacing jpg & png? The svg icons should be only compressed, without conversion. Would be nice to have a separate script in package.json specifically for these tasks.

When building, it should compress the converted images and copy them in dist/images.

I tried to do it for webp only and I received an error: 'EISDIR: illegal operation on a directory, read'

import fs from 'fs';
import sharp from 'sharp';

const files = fs.readdirSync('images');

const convert = (dir, name) => {
  const fullname = dir + '/' + name;
  const i = sharp(fs.readFileSync(fullname));
  i.toFormat('webp', { quality: 75 });
  return i
    .toFile('images/' + name + '.webp')
    .then(() => console.log('Converted', fullname))
    .catch((e) => console.log('Failed converting', fullname, e, 'skipping...'));
};

const promises = files.map((name) => convert('images/', name));

Promise.all(promises)
  .then(() => console.log('Done'))
  .catch((e) => console.error(e));
0 likes
0 replies

Please or to participate in this conversation.