-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathinline-critical-css.ts
76 lines (65 loc) · 2.17 KB
/
inline-critical-css.ts
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as fs from 'fs';
const Critters: typeof import('critters').default = require('critters');
export interface InlineCriticalCssProcessOptions {
outputPath: string;
}
export interface InlineCriticalCssProcessorOptions {
minify?: boolean;
deployUrl?: string;
readAsset?: (path: string) => Promise<string>;
}
class CrittersExtended extends Critters {
readonly warnings: string[] = [];
readonly errors: string[] = [];
constructor(
private readonly optionsExtended: InlineCriticalCssProcessorOptions &
InlineCriticalCssProcessOptions,
) {
super({
logger: {
warn: (s: string) => this.warnings.push(s),
error: (s: string) => this.errors.push(s),
info: () => {},
},
logLevel: 'warn',
path: optionsExtended.outputPath,
publicPath: optionsExtended.deployUrl,
compress: !!optionsExtended.minify,
pruneSource: false,
reduceInlineStyles: false,
mergeStylesheets: false,
preload: 'media',
noscriptFallback: true,
inlineFonts: true,
});
}
public override readFile(path: string): Promise<string> {
const readAsset = this.optionsExtended.readAsset;
return readAsset ? readAsset(path) : fs.promises.readFile(path, 'utf-8');
}
}
export class InlineCriticalCssProcessor {
constructor(protected readonly options: InlineCriticalCssProcessorOptions) {}
async process(
html: string,
options: InlineCriticalCssProcessOptions,
): Promise<{ content: string; warnings: string[]; errors: string[] }> {
const critters = new CrittersExtended({ ...this.options, ...options });
const content = await critters.process(html);
return {
// Clean up value from value less attributes.
// This is caused because parse5 always requires attributes to have a string value.
// nomodule="" defer="" -> nomodule defer.
content: content.replace(/(\s(?:defer|nomodule))=""/g, '$1'),
errors: critters.errors,
warnings: critters.warnings,
};
}
}