This repository has been archived by the owner on Jun 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
squoosh.js
61 lines (50 loc) · 1.85 KB
/
squoosh.js
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
const fs = require('fs');
const path = require('path');
const { ImagePool } = require('@squoosh/lib');
const imagePool = new ImagePool();
// Define your paths:
const imagesToOptimizePath = './src/images/';
// const moveToPath =
// './_originalRawImages/'; /* Uncomment this if you want to keep files */
const optimizeToPath = './static/';
(async () => {
const files = await fs.promises.readdir(imagesToOptimizePath);
for (const file of files) {
await libSquooshOptimize(file);
}
await imagePool.close();
})();
async function libSquooshOptimize(file) {
const imagePath = path.join(imagesToOptimizePath, file);
// const moveOriginalToPath = path.join(moveToPath, file); /* Uncomment this if you want to keep files */
const saveOptimizedImageToPath = path.join(
optimizeToPath,
path.parse(file).name,
);
console.log({ imagePath });
const image = imagePool.ingestImage(imagePath);
await image.decoded; // Wait until the image is decoded before running preprocessors
// const preprocessOptions = {
// resize: {
// enabled: true,
// width: 720,
// }
// };
// await image.preprocess(preprocessOptions);
const encodeOptions = {
// an empty object means 'use default settings'
webp: {},
oxipng: {},
};
await image.encode(encodeOptions);
for (const encodedImage of Object.values(image.encodedWith)) {
const { extension, binary } = await encodedImage;
const optimizedImagePath = `${saveOptimizedImageToPath}.${extension}`;
fs.writeFile(optimizedImagePath, binary, (err) => {
if (err) throw err;
console.log({ optimizedImagePath });
});
}
// move original image async
// await fs.promises.rename(imagePath, moveOriginalToPath); /* Uncomment this if you want to keep files */
}