forked from stawberri/imagemin-brunch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (80 loc) · 2.55 KB
/
index.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const fs = require("fs");
const imagemin = require("imagemin");
const loggy = require("loggy");
const plur = require("plur");
const prettyBytes = require("pretty-bytes");
const imageminPattern = /\.(gif|jpg|jpeg|jpe|jif|jfif|jfi|png|svg|svgz)$/;
const imageminPlugins = {
"imagemin-gifsicle": true,
"imagemin-jpegtran": true,
"imagemin-optipng": true,
"imagemin-svgo": true
};
exports = module.exports = class {
constructor(config) {
this.config = config.plugins.imagemin || {};
if (new Object(this.config.plugins) !== this.config.plugins)
this.config.plugins = {};
this.config.plugins = Object.assign(
{},
imageminPlugins,
this.config.plugins
);
this.plugins = [];
let pluginLoads = 0;
for (let plugin in this.config.plugins) {
let options = this.config.plugins[plugin];
if (!options) continue;
else pluginLoads++;
try {
if (new Object(options) === options)
this.plugins.push(require(plugin)(options));
else this.plugins.push(require(plugin)());
} catch (err) {
loggy.warn(`[imagemin] failed to load ${plugin}:`, err.message);
}
}
if (!this.plugins.length && pluginLoads)
throw new Error("No imagemin plugins loaded");
if (!("pattern" in this.config)) this.config.pattern = imageminPattern;
this.config.pattern = new RegExp(this.config.pattern);
}
onCompile(files, assets) {
let startTime = Date.now();
let promises = [];
let oldBytes = 0;
let newBytes = 0;
for (let asset of assets) {
if (!this.config.pattern.test(asset.destinationPath)) continue;
promises.push(
new Promise((res, rej) => {
let data = Buffer.from(asset.compiled);
oldBytes += data.length;
imagemin.buffer(data, { plugins: this.plugins }).then(buffer => {
newBytes += buffer.length;
fs.writeFile(asset.destinationPath, buffer, err => {
if (err) rej(err);
else res();
});
});
})
);
}
Promise.all(promises)
.then(() => {
let elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
let saved = prettyBytes(oldBytes - newBytes);
loggy.info(
`[imagemin] minified ${promises.length} ${plur(
"image",
promises.length
)} to save ${saved} in ${elapsed} sec`
);
})
.catch(err => {
loggy.error("[imagemin] minification failed:", err.message);
});
}
optimize() {}
};
exports.prototype.brunchPlugin = true;