-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcritical-css-postprocessor.js
More file actions
90 lines (74 loc) · 2.79 KB
/
critical-css-postprocessor.js
File metadata and controls
90 lines (74 loc) · 2.79 KB
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
/* eslint-disable no-console */
// Critical is loaded lazily to avoid ESM top-level await issues
let critical = null;
const PATH = require('path');
const _FILES_ = [
'base.html',
'index.html',
'action.html',
'ad.html',
];
const removeFilePart = dirname => PATH.basename(dirname);
var optimize_html_path = PATH.resolve('./static/', 'optimize/');
var index_critical_file = PATH.join(optimize_html_path, 'index_critical.html');
// Simple logger replacement for webpack-log
const log = {
info: (msg) => console.log('[ProcessAfterBuild]', msg),
error: (msg) => console.error('[ProcessAfterBuild]', msg)
};
class ProcessAfterBuild {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.hooks.beforeRun.tap('ProcessAfterBuild', compiler => { //write a combination of base and index html file to static/optimize/index_critical.html for creating critical css
const fs = require('fs');
const glob = require('glob');
if (!fs.existsSync(optimize_html_path)) {
fs.mkdirSync(optimize_html_path);
}
if (fs.existsSync(index_critical_file)) {
fs.unlinkSync(index_critical_file);
}
var files = glob('./pgaweb/templates/pgaweb/*.html', { sync: true });
files.forEach((filename_with_path) => {
let filename = removeFilePart(filename_with_path);
var readStream;
if (_FILES_.indexOf(filename) > -1) {
var buffer;
readStream = fs.createReadStream(filename_with_path, 'utf8');
readStream.on('data', function (chunk) {
buffer += chunk;
}).on('end', function () {
let index_critical_file = PATH.join(optimize_html_path, 'index_critical.html');
fs.appendFileSync(index_critical_file, buffer);
});
}
});
log.info('Critical html snippet generated successfully..');
}),
compiler.hooks.done.tapPromise('ProcessAfterBuild', async stats => { //logic for creating critical css based on combination of base and index html
const { path } = stats.compilation.options.output;
var cssPath = PATH.join(path, 'assets/css/');
// Lazy load critical to avoid ESM top-level await issues
if (!critical) {
critical = await import('critical');
critical = critical.default || critical;
}
critical.generate({
base: '/',
src: index_critical_file,
target: {
css: PATH.join(cssPath, 'main.css'),
uncritical: PATH.join(cssPath, 'main_uncritical.css'),
},
width: 1300,
height: 900,
// Extract inlined styles from referenced stylesheets
extract: true,
});
log.info('Critical css generated successfully..');
});
}
}
module.exports = ProcessAfterBuild;