This repository was archived by the owner on Jun 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpurify-css.js
57 lines (53 loc) · 1.8 KB
/
purify-css.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
const purifycss = require('../third_party/purify-css/purify-css');
const find = require('find');
const path = require('path');
const fs = require('fs');
const {promisify} = require('util');
preMinifyCss();
function preMinifyCss() {
find.file(/\/main\.css$/, 'build/', cssFiles => {
if (cssFiles.length != 1) {
throw new Error('Expected exactly 1 css file: ' + cssFiles.join(', '));
}
console.log('Input CSS', cssFiles[0]);
// First minify everything together. This makes the per file minify
// drastically faster, because we throw away 90% of the CSS here.
purifycss(['build/**/*.html'], cssFiles, {
info: true,
}, async function(css) {
console.info('Preprocessed CSS');
processHtml(css);
});
});
}
function processHtml(baseCss) {
find.file(/\.html$/, 'build/', htmls => {
htmls.forEach(async function(htmlFilename) {
console.log('Processing', htmlFilename);
let html = await promisify(fs.readFile)(htmlFilename, 'utf8');
if (/noindex/.test(html)) {
console.info('Skipping placeholder', htmlFilename);
return;
}
purifycss([htmlFilename], baseCss, {
// Comment in for debugging.
// rejected: true,
minify: true,
info: true,
}, async function(css) {
console.log('Done purifying', htmlFilename);
let html = await promisify(fs.readFile)(htmlFilename, 'utf8');
let found = false;
html = html.replace(/<link href=\S*\/css\/main.css\S* rel=stylesheet>/, match => {
found = true;
return '<style>' + css + '</style>';
});
if (!found) {
console.error('Cant find link element in ', htmlFilename);
throw new Error('Fail');
}
await promisify(fs.writeFile)(htmlFilename, html);
});
});
});
}