-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimize.js
executable file
·76 lines (68 loc) · 2.25 KB
/
optimize.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
const { Console } = require("console");
const fs = require("fs");
const path = require("path");
const imagemin = require("imagemin");
const imageminMozjpeg = require("imagemin-mozjpeg");
const imageminPngquant = require("imagemin-pngquant");
const imageminGiflossy = require("imagemin-giflossy");
const imageminSvgo = require("imagemin-svgo");
const logger = new Console(process.stdout, process.stderr);
const distDir = process.argv[2];
const walk = (dir, done) => {
let results = [];
fs.readdir(dir, (err, list) => {
if (err) {
return done(err);
}
let pending = list.length;
if (!pending) {
return done(null, results);
}
list.forEach((file) => {
file = path.resolve(dir, file);
fs.stat(file, (err, stat) => {
if (stat && stat.isDirectory()) {
walk(file, (err, res) => {
results = results.concat(res);
if (!--pending) {
done(null, results);
}
});
} else {
results.push(file);
if (!--pending) {
done(null, results);
}
}
});
});
});
};
if (!distDir) {
logger.error("Need \"dist\" path!");
return;
}
walk(distDir, (err, files) => {
if (err) {
logger.error(err);
return;
}
const images = files.filter((f) => /.*\.(gif|jpe?g|png|svg)$/.test(f));
images.forEach((f) => {
const fsize = fs.statSync(f).size;
imagemin([f], {
destination: path.resolve(f, ".."),
plugins: [
imageminMozjpeg({ quality: 70, dct: "float" }),
imageminPngquant({ quality: [0.65, 0.8], speed: 1, strip: true }),
imageminGiflossy({ lossy: 80, optimizationLevel: 3 }),
imageminSvgo()
]
}).then((done) => {
if (done[0]) {
const afsize = fs.statSync(done[0].destinationPath).size;
logger.log("optimized " + done[0].destinationPath + " (" + fsize + " -> " + afsize + ").");
}
}).catch(logger.error);
});
});