-
Notifications
You must be signed in to change notification settings - Fork 620
/
Copy pathModuleMinifierPlugin.ts
567 lines (479 loc) · 20 KB
/
ModuleMinifierPlugin.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import { createHash } from 'crypto';
import type { Comment } from 'estree';
import type {
Module,
Compilation,
WebpackPluginInstance,
Compiler,
javascript,
WebpackError,
ExternalModule,
sources,
Chunk
} from 'webpack';
import { AsyncSeriesWaterfallHook, SyncWaterfallHook, type Tap } from 'tapable';
import {
CHUNK_MODULE_TOKEN,
MODULE_WRAPPER_PREFIX,
MODULE_WRAPPER_SUFFIX,
STAGE_BEFORE,
STAGE_AFTER
} from './Constants';
import type {
IMinifierConnection,
IModuleMinifier,
IModuleMinificationResult,
IModuleMinificationErrorResult
} from '@rushstack/module-minifier';
import { getIdentifier } from '@rushstack/module-minifier';
import type {
IModuleMinifierPluginOptions,
IModuleMap,
IAssetMap,
IFactoryMeta,
IModuleMinifierPluginHooks,
IPostProcessFragmentContext,
IDehydratedAssets,
IModuleStats,
IModuleMinifierPluginStats as IModuleMinifierPluginStats,
IAssetStats
} from './ModuleMinifierPlugin.types';
import { generateLicenseFileForAsset } from './GenerateLicenseFileForAsset';
import { rehydrateAsset } from './RehydrateAsset';
// The name of the plugin, for use in taps
const PLUGIN_NAME: 'ModuleMinifierPlugin' = 'ModuleMinifierPlugin';
// Monotonically increasing identifier to be incremented any time the code generation logic changes
// Will be applied to the webpack hash.
const CODE_GENERATION_REVISION: number = 1;
// Match behavior of terser's "some" option
// https://github.com/terser/terser/blob/d3d924fa9e4c57bbe286b811c6068bcc7026e902/lib/output.js#L175
const LICENSE_COMMENT_REGEX: RegExp = /@preserve|@lic|@cc_on|^\**!/i;
const TAP_BEFORE: Tap = {
name: PLUGIN_NAME,
stage: STAGE_BEFORE
};
const TAP_AFTER: Tap = {
name: PLUGIN_NAME,
stage: STAGE_AFTER
};
interface IOptionsForHash extends Omit<IModuleMinifierPluginOptions, 'minifier'> {
revision: number;
minifier: undefined;
}
interface ISourceCacheEntry {
source: sources.Source;
hash: string;
}
const compilationMetadataMap: WeakMap<Compilation, IModuleMinifierPluginStats> = new WeakMap();
function hashCodeFragment(code: string): string {
return createHash('sha256').update(code).digest('hex');
}
/**
* Base implementation of asset rehydration
*
* @param dehydratedAssets The dehydrated assets
* @param compilation The webpack compilation
*/
function defaultRehydrateAssets(
dehydratedAssets: IDehydratedAssets,
compilation: Compilation
): IDehydratedAssets {
const { assets, modules } = dehydratedAssets;
const compilationMetadata: IModuleMinifierPluginStats | undefined = compilationMetadataMap.get(compilation);
if (!compilationMetadata) {
throw new Error(`Could not get compilation metadata`);
}
const { metadataByAssetFileName } = compilationMetadata;
// Now assets/modules contain fully minified code. Rehydrate.
for (const [assetName, info] of assets) {
const banner: string = info.type === 'javascript' ? generateLicenseFileForAsset(compilation, info) : '';
const replacementSource: sources.Source = rehydrateAsset(compilation, info, modules, banner, true);
metadataByAssetFileName.set(assetName, {
positionByModuleId: info.renderInfo
});
compilation.updateAsset(assetName, replacementSource);
}
return dehydratedAssets;
}
function isMinificationResultError(
result: IModuleMinificationResult
): result is IModuleMinificationErrorResult {
return !!result.error;
}
function isLicenseComment(comment: Comment): boolean {
return LICENSE_COMMENT_REGEX.test(comment.value);
}
/**
* Webpack plugin that minifies code on a per-module basis rather than per-asset. The actual minification is handled by the input `minifier` object.
* @public
*/
export class ModuleMinifierPlugin implements WebpackPluginInstance {
public readonly hooks: IModuleMinifierPluginHooks;
public minifier: IModuleMinifier;
private readonly _enhancers: WebpackPluginInstance[];
private readonly _sourceMap: boolean | undefined;
private readonly _optionsForHash: IOptionsForHash;
public constructor(options: IModuleMinifierPluginOptions) {
this.hooks = {
rehydrateAssets: new AsyncSeriesWaterfallHook(['dehydratedContent', 'compilation']),
postProcessCodeFragment: new SyncWaterfallHook(['code', 'context'])
};
const { minifier, sourceMap } = options;
this._optionsForHash = {
...options,
minifier: undefined,
revision: CODE_GENERATION_REVISION
};
this._enhancers = [];
this.hooks.rehydrateAssets.tap(PLUGIN_NAME, defaultRehydrateAssets);
this.minifier = minifier;
this._sourceMap = sourceMap;
}
public static getCompilationStatistics(compilation: Compilation): IModuleMinifierPluginStats | undefined {
return compilationMetadataMap.get(compilation);
}
public apply(compiler: Compiler): void {
for (const enhancer of this._enhancers) {
enhancer.apply(compiler);
}
const {
options: { devtool, mode },
webpack
} = compiler;
webpack.Template.numberToIdentifier = getIdentifier;
const { CachedSource, ConcatSource, RawSource, ReplaceSource, SourceMapSource } = webpack.sources;
// The explicit setting is preferred due to accuracy, but try to guess based on devtool
const useSourceMaps: boolean =
typeof this._sourceMap === 'boolean'
? this._sourceMap
: typeof devtool === 'string'
? devtool.endsWith('source-map')
: mode === 'production' && devtool !== false;
this._optionsForHash.sourceMap = useSourceMaps;
const binaryConfig: Buffer = Buffer.from(JSON.stringify(this._optionsForHash), 'utf-8');
compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation, compilationData) => {
const { normalModuleFactory } = compilationData;
function addCommentExtraction(parser: javascript.JavascriptParser): void {
parser.hooks.program.tap(PLUGIN_NAME, (program: unknown, comments: Comment[]) => {
const relevantComments: Comment[] = comments.filter(isLicenseComment);
if (comments.length > 0) {
// Webpack's typings now restrict the properties on factoryMeta for unknown reasons
const module: { factoryMeta?: IFactoryMeta } = parser.state.module as unknown as {
factoryMeta?: IFactoryMeta;
};
if (!module.factoryMeta) {
module.factoryMeta = {
comments: relevantComments
};
} else {
(module.factoryMeta as IFactoryMeta).comments = relevantComments;
}
}
});
}
normalModuleFactory.hooks.parser.for('javascript/auto').tap(PLUGIN_NAME, addCommentExtraction);
normalModuleFactory.hooks.parser.for('javascript/dynamic').tap(PLUGIN_NAME, addCommentExtraction);
normalModuleFactory.hooks.parser.for('javascript/esm').tap(PLUGIN_NAME, addCommentExtraction);
/**
* Set of local module ids that have been processed.
*/
const submittedModules: Set<string | number> = new Set();
/**
* The text and comments of all minified modules.
*/
const minifiedModules: IModuleMap = new Map();
/**
* The text and comments of all minified chunks. Most of these are trivial, but the runtime chunk is a bit larger.
*/
const minifiedAssets: IAssetMap = new Map();
const metadataByModule: WeakMap<Module, IModuleStats> = new WeakMap();
const metadataByAssetFileName: Map<string, IAssetStats> = new Map();
const compilationStatistics: IModuleMinifierPluginStats = {
metadataByModule,
metadataByAssetFileName
};
compilationMetadataMap.set(compilation, compilationStatistics);
function getOrCreateMetadata(mod: Module): IModuleStats {
let moduleStats: IModuleStats | undefined = metadataByModule.get(mod);
if (!moduleStats) {
moduleStats = {
hashByChunk: new Map(),
sizeByHash: new Map()
};
metadataByModule.set(mod, moduleStats);
}
return moduleStats;
}
let pendingMinificationRequests: number = 0;
/**
* Indicates that all files have been sent to the minifier and therefore that when pending hits 0, assets can be rehydrated.
*/
let allRequestsIssued: boolean = false;
let resolveMinifyPromise: () => void;
const postProcessCode: (
code: sources.ReplaceSource,
context: IPostProcessFragmentContext
) => sources.ReplaceSource = (code: sources.ReplaceSource, context: IPostProcessFragmentContext) =>
this.hooks.postProcessCodeFragment.call(code, context);
/**
* Callback to invoke when a file has finished minifying.
*/
function onFileMinified(): void {
if (--pendingMinificationRequests === 0 && allRequestsIssued) {
resolveMinifyPromise();
}
}
const { minifier } = this;
let minifierConnection: IMinifierConnection | undefined;
// Typings for this object are not exposed
// eslint-disable-next-line @typescript-eslint/typedef
const javascriptHooks = webpack.javascript.JavascriptModulesPlugin.getCompilationHooks(compilation);
/**
* The minifier needs to know if the module was wrapped in a factory function, because
* function (module, exports, require) { // <implementation> }
* minifies to nothing. Unfortunately we can't tell by inspection if the output was wrapped or not.
* However, the JavaScriptModulesPlugin invokes three hooks in order when rendering a module:
* 1) renderModuleContent - Invoked for every module.
* 2) renderModuleContainer - Invoked when wrapping a module in a factory.
* 3) renderModulePackage - Invoked for every module as the last hook.
*/
let nextModule: Module | undefined;
const sourceCache: WeakMap<sources.Source, ISourceCacheEntry> = new WeakMap();
javascriptHooks.renderModuleContent.tap(TAP_AFTER, (source) => {
// Clear the identification state of the current module.
nextModule = undefined;
return source;
});
javascriptHooks.renderModuleContainer.tap(TAP_AFTER, (source, mod) => {
// Module is being wrapped in a factory, so it is safe for per-module minification
// Leave external modules in-place to avoid needing special handling for externals
if (mod.context !== null || !(mod as ExternalModule).externalType) {
nextModule = mod;
}
return source;
});
javascriptHooks.renderModulePackage.tap(
TAP_AFTER,
/**
* Extracts the code for the module and sends it to be minified.
*/
function minifyModule(
source: sources.Source,
mod: Module,
chunkRenderContext: { chunk: Chunk }
): sources.Source {
if (nextModule !== mod) {
// This module is being inlined. Abandon per-module minification.
return source;
}
const id: string | number | null = compilation.chunkGraph.getModuleId(mod);
if (id === null) {
// This module has no id. Abandon per-module minification.
return source;
}
const metadata: IModuleStats = getOrCreateMetadata(mod);
const cachedResult: ISourceCacheEntry | undefined = sourceCache.get(source);
if (cachedResult) {
metadata.hashByChunk.set(chunkRenderContext.chunk, cachedResult.hash);
return cachedResult.source;
}
// If this module is wrapped in a factory, need to add boilerplate so that the minifier keeps the function
const wrapped: sources.Source = new ConcatSource(
MODULE_WRAPPER_PREFIX + '\n',
source,
'\n' + MODULE_WRAPPER_SUFFIX
);
const nameForMap: string = `(modules)/${id}`;
const { source: wrappedCodeRaw, map } = useSourceMaps
? wrapped.sourceAndMap()
: {
source: wrapped.source(),
map: undefined
};
const wrappedCode: string = wrappedCodeRaw.toString();
const hash: string = hashCodeFragment(wrappedCode);
metadata.hashByChunk.set(chunkRenderContext.chunk, hash);
if (!submittedModules.has(hash)) {
submittedModules.add(hash);
++pendingMinificationRequests;
minifier.minify(
{
hash,
code: wrappedCode,
nameForMap: useSourceMaps ? nameForMap : undefined,
externals: undefined
},
(result: IModuleMinificationResult) => {
if (isMinificationResultError(result)) {
compilation.errors.push(result.error as WebpackError);
} else {
try {
const { code: minified, map: minifierMap } = result;
const rawOutput: sources.Source = useSourceMaps
? new SourceMapSource(
minified, // Code
nameForMap, // File
minifierMap!, // Base source map
wrappedCode, // Source from before transform
map!, // Source Map from before transform
true // Remove original source
)
: new RawSource(minified);
const unwrapped: sources.ReplaceSource = new ReplaceSource(rawOutput);
const len: number = minified.length;
// Trim off the boilerplate used to preserve the factory
unwrapped.replace(0, MODULE_WRAPPER_PREFIX.length - 1, '');
unwrapped.replace(len - MODULE_WRAPPER_SUFFIX.length, len - 1, '');
const withIds: sources.Source = postProcessCode(unwrapped, {
compilation,
module: mod,
loggingName: mod.identifier()
});
const cached: sources.CachedSource = new CachedSource(withIds);
const minifiedSize: number = Buffer.byteLength(cached.source(), 'utf-8');
metadata.sizeByHash.set(hash, minifiedSize);
minifiedModules.set(hash, {
source: cached,
module: mod,
id
});
} catch (err) {
compilation.errors.push(err);
}
}
onFileMinified();
}
);
}
const result: sources.Source = new RawSource(`${CHUNK_MODULE_TOKEN}${hash}`);
sourceCache.set(source, {
hash,
source: result
});
// Return an expression to replace later
return result;
}
);
// The optimizeChunkModules hook is the last async hook that occurs before chunk rendering
compilation.hooks.optimizeChunkModules.tapPromise(PLUGIN_NAME, async () => {
minifierConnection = await minifier.connectAsync();
submittedModules.clear();
});
const isJSAsset: RegExp = /\.[cm]?js(\?.+)?$/;
// This should happen before any other tasks that operate during processAssets
compilation.hooks.processAssets.tapPromise(TAP_BEFORE, async (): Promise<void> => {
const { chunkGraph, chunks } = compilation;
// Still need to minify the rendered assets
for (const chunk of chunks) {
const allChunkModules: Iterable<Module> | undefined =
chunkGraph.getChunkModulesIterableBySourceType(chunk, 'javascript');
if (!allChunkModules) {
// This chunk does not contain javascript modules
continue;
}
for (const assetName of chunk.files) {
const asset: sources.Source = compilation.assets[assetName];
// Verify that this is a JS asset
if (isJSAsset.test(assetName)) {
++pendingMinificationRequests;
const { source: wrappedCodeRaw, map } = useSourceMaps
? asset.sourceAndMap()
: {
source: asset.source(),
map: undefined
};
const rawCode: string = wrappedCodeRaw.toString();
const nameForMap: string = `(chunks)/${assetName}`;
const hash: string = hashCodeFragment(rawCode);
minifier.minify(
{
hash,
code: rawCode,
nameForMap: useSourceMaps ? nameForMap : undefined,
externals: undefined
},
(result: IModuleMinificationResult) => {
if (isMinificationResultError(result)) {
compilation.errors.push(result.error as WebpackError);
// eslint-disable-next-line no-console
console.error(result.error);
} else {
try {
const { code: minified, map: minifierMap } = result;
const rawOutput: sources.Source = useSourceMaps
? new SourceMapSource(
minified, // Code
nameForMap, // File
minifierMap!, // Base source map
rawCode, // Source from before transform
map, // Source Map from before transform
true // Remove original source
)
: new RawSource(minified);
const withIds: sources.Source = postProcessCode(new ReplaceSource(rawOutput), {
compilation,
module: undefined,
loggingName: assetName
});
minifiedAssets.set(assetName, {
source: new CachedSource(withIds),
chunk,
fileName: assetName,
renderInfo: new Map(),
type: 'javascript'
});
} catch (err) {
compilation.errors.push(err);
}
}
onFileMinified();
}
);
} else {
// This isn't a JS asset. Don't try to minify the asset wrapper, though if it contains modules, those might still get replaced with minified versions.
minifiedAssets.set(assetName, {
// Still need to restore ids
source: postProcessCode(new ReplaceSource(asset), {
compilation,
module: undefined,
loggingName: assetName
}),
chunk,
fileName: assetName,
renderInfo: new Map(),
type: 'unknown'
});
}
}
}
allRequestsIssued = true;
if (pendingMinificationRequests) {
await new Promise<void>((resolve) => {
resolveMinifyPromise = resolve;
});
}
// Handle any error from the minifier.
await minifierConnection?.disconnectAsync();
// All assets and modules have been minified, hand them off to be rehydrated
await this.hooks.rehydrateAssets.promise(
{
assets: minifiedAssets,
modules: minifiedModules
},
compilation
);
});
// Need to update chunk hashes with information from this plugin
javascriptHooks.chunkHash.tap(PLUGIN_NAME, (chunk, hash): void => {
// Apply the options hash
hash.update(binaryConfig);
// Apply the hash from the minifier
if (minifierConnection) {
hash.update(minifierConnection.configHash, 'utf8');
}
});
});
}
}