|
1
|
|
|
import {Plugin} from 'rollup'; |
|
2
|
|
|
import path from 'path'; |
|
3
|
|
|
const critical = require('critical'); |
|
4
|
|
|
|
|
5
|
|
|
const criticalSuffix = '_critical.min.css'; |
|
6
|
|
|
|
|
7
|
|
|
const defaultCriticalConfig = { |
|
8
|
|
|
base: './', |
|
9
|
|
|
inline: false, |
|
10
|
|
|
minify: true, |
|
11
|
|
|
extract: false, |
|
12
|
|
|
width: 1200, |
|
13
|
|
|
height: 1200, |
|
14
|
|
|
concurrency: 4, |
|
15
|
|
|
penthouse: { |
|
16
|
|
|
blockJSRequests: false |
|
17
|
|
|
} |
|
18
|
|
|
}; |
|
19
|
|
|
|
|
20
|
|
|
interface CriticalPages { |
|
21
|
|
|
uri: string; |
|
22
|
|
|
template: string; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
interface CriticalPluginConfig { |
|
26
|
|
|
criticalUrl: string; |
|
27
|
|
|
criticalBase?: string; |
|
28
|
|
|
pages: Partial<CriticalPages>[]; |
|
29
|
|
|
criticalConfig?: Partial<CriticalConfig>; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
function PluginCritical(pluginConfig: CriticalPluginConfig, callback?: Function): Plugin { |
|
33
|
|
|
return { |
|
34
|
|
|
name: 'critical', |
|
35
|
|
|
async writeBundle(outputOptions, bundle) { |
|
36
|
|
|
const css: Array<string> = []; |
|
37
|
|
|
// Find all of the generated CSS assets |
|
38
|
|
|
if (bundle) { |
|
39
|
|
|
for (const chunk of Object.values(bundle)) { |
|
40
|
|
|
if (chunk.type === 'asset' && chunk.fileName.endsWith('.css')) { |
|
41
|
|
|
if (outputOptions.dir !== undefined) { |
|
42
|
|
|
const cssFile = path.join(outputOptions.dir, chunk.fileName); |
|
43
|
|
|
css.push(cssFile); |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
// If we have no CSS, skip bundle |
|
48
|
|
|
if (!css.length) { |
|
49
|
|
|
return; |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
// Iterate through the pages |
|
53
|
|
|
for (const page of pluginConfig.pages) { |
|
54
|
|
|
const criticalBase = pluginConfig.criticalBase; |
|
55
|
|
|
const criticalSrc = pluginConfig.criticalUrl + page.uri; |
|
56
|
|
|
const criticalDest = page.template + criticalSuffix; |
|
57
|
|
|
// Merge in our options |
|
58
|
|
|
const options = Object.assign( |
|
59
|
|
|
{ css }, |
|
60
|
|
|
defaultCriticalConfig, |
|
61
|
|
|
{ |
|
62
|
|
|
base: criticalBase, |
|
63
|
|
|
src: criticalSrc, |
|
64
|
|
|
target: criticalDest, |
|
65
|
|
|
}, |
|
66
|
|
|
pluginConfig.criticalConfig |
|
67
|
|
|
); |
|
68
|
|
|
// Generate the Critical CSS |
|
69
|
|
|
console.log(`Generating critical CSS from ${criticalSrc} to ${criticalDest}`); |
|
70
|
|
|
await critical.generate(options, (err: string) => { |
|
71
|
|
|
if (err) { |
|
72
|
|
|
console.error(err); |
|
73
|
|
|
} |
|
74
|
|
|
if (callback) { |
|
75
|
|
|
callback(err); |
|
76
|
|
|
} |
|
77
|
|
|
}); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
}; |
|
82
|
|
|
|
|
83
|
|
|
export default PluginCritical |
|
84
|
|
|
|