1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| import images from 'images'; import imagemin from 'imagemin'; import imageminMozjpeg from 'imagemin-mozjpeg'; import imageminPngquant from 'imagemin-pngquant'; import fsPromises from 'fs/promises'; import path from 'path'; import convertToUnixPath from 'slash'; import { getAllFiles } from 'get-all-files';
const handleFile = async (sourcePath) => { if (images(sourcePath).width() > 375 * 2) { const fileType = path.extname(sourcePath).replace('.', '').toLowerCase();
const buffer = await imagemin.buffer( images(sourcePath) .size(375 * 2) .toBuffer(fileType), { plugins: [ imageminMozjpeg({ quality: 70 }), imageminPngquant({ quality: [0.6, 0.8], }), ], } );
const destinationPath = path.join('./build', path.basename(sourcePath).toLowerCase());
await fsPromises.mkdir(path.dirname(destinationPath), { recursive: true });
await fsPromises.writeFile(destinationPath, buffer); return; }
await imagemin([sourcePath], { destination: 'build', plugins: [ imageminMozjpeg({ quality: 70 }), imageminPngquant({ quality: [0.6, 0.8], }), ], }); };
getAllFiles('./images') .toArray() .then((paths) => { return paths .map((it) => convertToUnixPath(it)) .filter((it) => { const ext = path.extname(it).toLowerCase();
return ['.jpg', '.jpeg', '.png'].includes(ext); }); }) .then((paths) => { return paths.map(async (p) => { try { return await handleFile(p); } catch (err) { throw err; } }); });
|