-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathoptimize.js
49 lines (44 loc) · 1.23 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
const fs = require("fs");
const glob = require("glob");
const htmlnano = require("htmlnano");
const ampSafePreset = require("htmlnano").presets.ampSafe;
const postcss = require("./postcss.config");
const publicDir = `${__dirname}/public`;
const options = {
removeComments: "all",
collapseWhitespace: "conservative",
removeUnusedCss: {
tool: "purgeCSS",
...postcss.purgeCssWhitelist,
},
};
const optimizePage = async (file) => {
console.log(`Optimizing file ${file}`);
try {
const { html } = await htmlnano.process(
fs.readFileSync(file, "utf8"),
options,
ampSafePreset
);
fs.writeFileSync(file, html);
} catch (error) {
console.error({ error });
throw error;
}
};
// Separate the array into chunks of a specific size
const toChunks = (arr, size) => {
return Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
};
const main = async () => {
const files = glob.sync(`${publicDir}/**/*.html`);
// Split the array into chunks, else it will throw a memory error
const chunks = toChunks(files, 500);
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
await Promise.all(chunk.map(optimizePage));
}
};
main();