-
Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathcss-optimizer-plugin.ts
193 lines (164 loc) · 6.61 KB
/
css-optimizer-plugin.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
/**
* @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 type { Message, TransformResult } from 'esbuild';
import type { Compilation, Compiler, sources } from 'webpack';
import { addWarning } from '../../utils/webpack-diagnostics';
import { EsbuildExecutor } from './esbuild-executor';
/**
* The name of the plugin provided to Webpack when tapping Webpack compiler hooks.
*/
const PLUGIN_NAME = 'angular-css-optimizer';
export interface CssOptimizerPluginOptions {
supportedBrowsers?: string[];
}
/**
* A Webpack plugin that provides CSS optimization capabilities.
*
* The plugin uses both `esbuild` to provide both fast and highly-optimized
* code output.
*/
export class CssOptimizerPlugin {
private targets: string[] | undefined;
private esbuild = new EsbuildExecutor();
constructor(options?: CssOptimizerPluginOptions) {
if (options?.supportedBrowsers) {
this.targets = this.transformSupportedBrowsersToTargets(options.supportedBrowsers);
}
}
apply(compiler: Compiler) {
const { OriginalSource, SourceMapSource } = compiler.webpack.sources;
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
const logger = compilation.getLogger('build-angular.CssOptimizerPlugin');
compilation.hooks.processAssets.tapPromise(
{
name: PLUGIN_NAME,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE,
},
async (compilationAssets) => {
const cache = compilation.options.cache && compilation.getCache(PLUGIN_NAME);
logger.time('optimize css assets');
for (const assetName of Object.keys(compilationAssets)) {
if (!/\.(?:css|scss|sass|less|styl)$/.test(assetName)) {
continue;
}
const asset = compilation.getAsset(assetName);
// Skip assets that have already been optimized or are verbatim copies (project assets)
if (!asset || asset.info.minimized || asset.info.copied) {
continue;
}
const { source: styleAssetSource, name } = asset;
let cacheItem;
if (cache) {
const eTag = cache.getLazyHashedEtag(styleAssetSource);
cacheItem = cache.getItemCache(name, eTag);
const cachedOutput = await cacheItem.getPromise<
{ source: sources.Source; warnings: Message[] } | undefined
>();
if (cachedOutput) {
logger.debug(`${name} restored from cache`);
await this.addWarnings(compilation, cachedOutput.warnings);
compilation.updateAsset(name, cachedOutput.source, (assetInfo) => ({
...assetInfo,
minimized: true,
}));
continue;
}
}
const { source, map: inputMap } = styleAssetSource.sourceAndMap();
const input = typeof source === 'string' ? source : source.toString();
const optimizeAssetLabel = `optimize asset: ${asset.name}`;
logger.time(optimizeAssetLabel);
const { code, warnings, map } = await this.optimize(
input,
asset.name,
inputMap,
this.targets,
);
logger.timeEnd(optimizeAssetLabel);
await this.addWarnings(compilation, warnings);
const optimizedAsset = map
? new SourceMapSource(code, name, map)
: new OriginalSource(code, name);
compilation.updateAsset(name, optimizedAsset, (assetInfo) => ({
...assetInfo,
minimized: true,
}));
await cacheItem?.storePromise({
source: optimizedAsset,
warnings,
});
}
logger.timeEnd('optimize css assets');
},
);
});
}
/**
* Optimizes a CSS asset using esbuild.
*
* @param input The CSS asset source content to optimize.
* @param name The name of the CSS asset. Used to generate source maps.
* @param inputMap Optionally specifies the CSS asset's original source map that will
* be merged with the intermediate optimized source map.
* @param target Optionally specifies the target browsers for the output code.
* @returns A promise resolving to the optimized CSS, source map, and any warnings.
*/
private optimize(
input: string,
name: string,
inputMap: object,
target: string[] | undefined,
): Promise<TransformResult> {
let sourceMapLine;
if (inputMap) {
// esbuild will automatically remap the sourcemap if provided
sourceMapLine = `\n/*# sourceMappingURL=data:application/json;charset=utf-8;base64,${Buffer.from(
JSON.stringify(inputMap),
).toString('base64')} */`;
}
return this.esbuild.transform(sourceMapLine ? input + sourceMapLine : input, {
loader: 'css',
legalComments: 'inline',
minify: true,
sourcemap: !!inputMap && 'external',
sourcefile: name,
target,
});
}
private async addWarnings(compilation: Compilation, warnings: Message[]) {
if (warnings.length > 0) {
for (const warning of await this.esbuild.formatMessages(warnings, { kind: 'warning' })) {
addWarning(compilation, warning);
}
}
}
private transformSupportedBrowsersToTargets(supportedBrowsers: string[]): string[] | undefined {
const transformed: string[] = [];
// https://esbuild.github.io/api/#target
const esBuildSupportedBrowsers = new Set(['safari', 'firefox', 'edge', 'chrome', 'ios']);
for (const browser of supportedBrowsers) {
let [browserName, version] = browser.split(' ');
// browserslist uses the name `ios_saf` for iOS Safari whereas esbuild uses `ios`
if (browserName === 'ios_saf') {
browserName = 'ios';
}
// browserslist uses ranges `15.2-15.3` versions but only the lowest is required
// to perform minimum supported feature checks. esbuild also expects a single version.
[version] = version.split('-');
if (esBuildSupportedBrowsers.has(browserName)) {
if (browserName === 'safari' && version === 'TP') {
// esbuild only supports numeric versions so `TP` is converted to a high number (999) since
// a Technology Preview (TP) of Safari is assumed to support all currently known features.
version = '999';
}
transformed.push(browserName + version);
}
}
return transformed.length ? transformed : undefined;
}
}