-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathany-component-style-budget-checker.ts
91 lines (81 loc) · 2.55 KB
/
any-component-style-budget-checker.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* @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.dev/license
*/
import {
BudgetAsset,
BudgetEntry,
BudgetType,
ThresholdSeverity,
checkBudgets,
} from '@angular/build/private';
import * as path from 'node:path';
import { Compilation, Compiler } from 'webpack';
import { addError, addWarning } from '../../../utils/webpack-diagnostics';
const PLUGIN_NAME = 'AnyComponentStyleBudgetChecker';
/**
* Check budget sizes for component styles by emitting a warning or error if a
* budget is exceeded by a particular component's styles.
*/
export class AnyComponentStyleBudgetChecker {
private readonly budgets: BudgetEntry[];
constructor(budgets: BudgetEntry[]) {
this.budgets = budgets.filter((budget) => budget.type === BudgetType.AnyComponentStyle);
}
apply(compiler: Compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
compilation.hooks.processAssets.tap(
{
name: PLUGIN_NAME,
stage: Compilation.PROCESS_ASSETS_STAGE_ANALYSE,
},
() => {
// No budgets.
if (this.budgets.length === 0) {
return;
}
// In AOT compilations component styles get processed in child compilations.
if (!compilation.compiler.parentCompilation) {
return;
}
const cssExtensions = ['.css', '.scss', '.less', '.sass'];
const componentStyles: BudgetAsset[] = Object.keys(compilation.assets)
.filter((name) => cssExtensions.includes(path.extname(name)))
.map((name) => ({
name,
size: compilation.assets[name].size(),
componentStyle: true,
}));
for (const { severity, message } of checkBudgets(
this.budgets,
{ chunks: [], assets: componentStyles },
true,
)) {
switch (severity) {
case ThresholdSeverity.Warning:
addWarning(compilation, message);
break;
case ThresholdSeverity.Error:
addError(compilation, message);
break;
default:
assertNever(severity);
}
}
},
);
});
}
}
function assertNever(input: never): never {
throw new Error(
`Unexpected call to assertNever() with input: ${JSON.stringify(
input,
null /* replacer */,
4 /* tabSize */,
)}`,
);
}