-
Notifications
You must be signed in to change notification settings - Fork 0
/
min.js
77 lines (65 loc) · 2.32 KB
/
min.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
"use strict";
const Buffer = require("buffer").Buffer;
const fs = require("fs");
const path = require("path");
const csso = require("csso");
const terser = require("terser");
const svgo = require("svgo");
const utils = require("./utils");
exports.run = async function(directory) {
let stats = {
css: { count: 0, ogSize: 0, minSize: 0, skip: 0 },
js: { count: 0, ogSize: 0, minSize: 0, skip: 0 },
svg: { count: 0, ogSize: 0, minSize: 0, skip: 0 },
};
let startTime = process.hrtime.bigint();
for (let p of utils.walkDir(directory)) {
let ext = path.extname(p);
if (![".css", ".js", ".mjs", ".svg"].includes(ext)) {
continue;
}
let og = fs.readFileSync(p, "utf8");
let ogSize = fs.statSync(p).size;
let type, min;
try {
switch (ext) {
case ".css":
type = "css";
min = csso.minify(og).css;
break;
case ".js":
case ".mjs":
type = "js";
min = terser.minify_sync(og).code;
break;
case ".svg":
type = "svg";
min = svgo.optimize(og).data;
break;
}
} catch (e) {
console.error(`min: Error minifying "${utils.urlPath(directory, p)}"`);
}
if (min == null) {
min = og;
}
if (Buffer.byteLength(min, "utf8") < Buffer.byteLength(og, "utf8")) {
fs.writeFileSync(p, min);
} else {
min = og;
stats[type].skip += 1;
}
stats[type].count += 1;
stats[type].ogSize += ogSize;
stats[type].minSize += fs.statSync(p).size;
}
let endTime = process.hrtime.bigint();
let duration = utils.humanDuration(endTime - startTime);
console.log(`min: Took ${duration} to complete`);
for (let type of ["css", "js", "svg"]) {
let ogSize = utils.humanSize(stats[type].ogSize);
let minSize = utils.humanSize(stats[type].minSize);
let savings = 100 - (stats[type].ogSize === 0 ? 100 : stats[type].minSize/stats[type].ogSize * 100);
console.log(` ${type}: ${ogSize} => ${minSize} (saved ${savings.toFixed(2)}%) -- ${stats[type].count} file(s), skipped ${stats[type].skip} file(s)`);
}
}