-
-
Notifications
You must be signed in to change notification settings - Fork 33
/
WebpackAssetsManifest.js
670 lines (561 loc) · 17.1 KB
/
WebpackAssetsManifest.js
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
/**
* Webpack Assets Manifest
*
* @author Eric King <eric@webdeveric.com>
*/
'use strict';
const fs = require('fs');
const url = require('url');
const path = require('path');
const get = require('lodash.get');
const has = require('lodash.has');
const validateOptions = require('schema-utils');
const { SyncHook, SyncWaterfallHook } = require('tapable');
const { RawSource } = require('webpack-sources');
const optionsSchema = require('./options-schema.json');
const {
maybeArrayWrap,
filterHashes,
getSRIHash,
warn,
varType,
getSortedObject,
} = require('./helpers.js');
const IS_MERGING = Symbol('isMerging');
const PLUGIN_NAME = 'WebpackAssetsManifest';
class WebpackAssetsManifest
{
/**
* @param {object} options - configuration options
* @constructor
*/
constructor(options = {})
{
/**
* This is using hooks from {@link https://github.com/webpack/tapable Tapable}.
*/
this.hooks = {
apply: new SyncHook([ 'manifest' ]),
customize: new SyncWaterfallHook([ 'entry', 'original', 'manifest', 'asset' ]),
transform: new SyncWaterfallHook([ 'assets', 'manifest' ]),
done: new SyncHook([ 'manifest', 'stats' ]),
options: new SyncWaterfallHook([ 'options' ]),
afterOptions: new SyncHook([ 'options' ]),
};
this.hooks.transform.tap(PLUGIN_NAME, assets => {
const { sortManifest } = this.options;
return sortManifest ? getSortedObject(
assets,
typeof sortManifest === 'function' ? sortManifest.bind(this) : undefined
) : assets;
});
this.hooks.afterOptions.tap(PLUGIN_NAME, options => {
this.options = Object.assign( this.defaultOptions, options );
this.options.integrityHashes = filterHashes( this.options.integrityHashes );
validateOptions(optionsSchema, this.options, { name: PLUGIN_NAME });
// Copy over any entries that may have been added to the manifest before apply() was called.
// If the same key exists in assets and options.assets, options.assets should be used.
this.assets = Object.assign(this.options.assets, this.assets, this.options.assets);
if ( has( this.options, 'contextRelativeKeys' ) ) {
warn('contextRelativeKeys has been removed. Please use the customize hook instead.');
}
[ 'apply', 'customize', 'transform', 'done' ].forEach( hookName => {
if ( typeof this.options[ hookName ] === 'function' ) {
this.hooks[ hookName ].tap(`${PLUGIN_NAME}.option.${hookName}`, this.options[ hookName ] );
}
});
});
this.options = Object.assign( this.defaultOptions, options );
// This is what gets JSON stringified
this.assets = this.options.assets;
// original filename : hashed filename
this.assetNames = new Map();
// This is passed to the customize() hook
this.currentAsset = null;
// The Webpack compiler instance
this.compiler = null;
// compilation stats
this.stats = null;
// This is used to identify hot module replacement files
this.hmrRegex = null;
// Is a merge happening?
this[ IS_MERGING ] = false;
}
/**
* Hook into the Webpack compiler
*
* @param {object} compiler - The Webpack compiler object
*/
apply(compiler)
{
this.compiler = compiler;
// Allow hooks to modify options
this.options = this.hooks.options.call(this.options);
// Ensure options contain defaults and are valid
this.hooks.afterOptions.call(this.options);
const { output: { filename, hotUpdateChunkFilename } } = compiler.options;
if ( filename !== hotUpdateChunkFilename && typeof hotUpdateChunkFilename === 'string' ) {
this.hmrRegex = new RegExp(
hotUpdateChunkFilename
.replace(/\./g, '\\.')
.replace(/\[[a-z]+(:\d+)?\]/gi, (m, n) => (n ? `.{${n.substr(1)}}` : '.+')) + '$',
'i'
);
}
// compilation.assets contains the results of the build
compiler.hooks.compilation.tap(PLUGIN_NAME, this.handleCompilation.bind(this));
// Add manifest.json to compiler.assets
compiler.hooks.emit.tapAsync(PLUGIN_NAME, this.handleEmit.bind(this));
// Use fs to write the manifest.json to disk if `options.writeToDisk` is true
compiler.hooks.afterEmit.tapPromise(PLUGIN_NAME, this.handleAfterEmit.bind(this));
// The compilation has finished
compiler.hooks.done.tap(PLUGIN_NAME, stats => this.hooks.done.call(this, stats));
// Setup is complete.
this.hooks.apply.call(this);
}
/**
* Get the default options.
*
* @return {object}
*/
get defaultOptions()
{
return {
assets: Object.create(null),
output: 'manifest.json',
replacer: null, // Its easier to use the transform hook instead.
space: 2,
writeToDisk: false,
fileExtRegex: /\.\w{2,4}\.(?:map|gz)$|\.\w+$/i,
sortManifest: true,
merge: false,
publicPath: null,
// Hooks
apply: null, // After setup is complete
customize: null, // Customize each entry in the manifest
transform: null, // Transform the entire manifest
done: null, // Compilation is done and the manifest has been written
// Include `compilation.entrypoints` in the manifest file
entrypoints: false,
entrypointsKey: 'entrypoints',
// https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
integrity: false,
integrityHashes: [ 'sha256', 'sha384', 'sha512' ],
integrityPropertyName: 'integrity',
};
}
/**
* Determine if the manifest data is currently being merged.
*
* @return {boolean}
*/
get isMerging()
{
return this[ IS_MERGING ];
}
/**
* Get the file extension.
*
* @param {string} filename
* @return {string}
*/
getExtension(filename)
{
if (! filename || typeof filename !== 'string') {
return '';
}
filename = filename.split(/[?#]/)[0];
if (this.options.fileExtRegex) {
const ext = filename.match(this.options.fileExtRegex);
return ext && ext.length ? ext[ 0 ] : '';
}
return path.extname(filename);
}
/**
* Replace backslash with forward slash.
*
* @return {string}
*/
fixKey(key)
{
return typeof key === 'string' ? key.replace( /\\/g, '/' ) : key;
}
/**
* Determine if the filename matches the HMR filename pattern.
*
* @return {boolean}
*/
isHMR(filename)
{
return this.hmrRegex ? this.hmrRegex.test( filename ) : false;
}
/**
* Add item to assets without modifying the key or value.
*
* @param {string} key
* @param {string} value
* @return {object} this
*/
setRaw(key, value)
{
this.assets[ key ] = value;
return this;
}
/**
* Add an item to the manifest.
*
* @param {string} key
* @param {string} value
* @return {object} this
*/
set(key, value)
{
if ( this.isMerging && this.options.merge !== 'customize' ) {
// Do not fix the key if merging since it should already be correct.
return this.setRaw(key, value);
}
const fixedKey = this.fixKey(key);
const publicPath = this.getPublicPath( value );
const entry = this.hooks.customize.call(
{
key: fixedKey,
value: publicPath,
},
{
key,
value,
},
this,
this.currentAsset
);
// Allow the entry to be skipped
if ( entry === false ) {
return this;
}
// Use the customized values
if ( varType(entry) === 'Object' ) {
let { key = fixedKey, value = publicPath } = entry;
// If the integrity should be returned but the entry value was
// not customized lets do that now so it includes both.
if ( value === publicPath && this.options.integrity ) {
value = {
src: value,
integrity: get(this, `currentAsset.${this.options.integrityPropertyName}`, ''),
};
}
return this.setRaw( key, value );
}
warn.once(`Unexpected customize() return type: ${varType(entry)}`);
return this.setRaw( fixedKey, publicPath );
}
/**
* Determine if an item exist in the manifest.
*
* @param {string} key
* @return {boolean}
*/
has(key)
{
return has(this.assets, key) || has(this.assets, this.fixKey(key));
}
/**
* Get an item from the manifest.
*
* @param {string} key
* @param {string} defaultValue - Defaults to empty string
* @return {*}
*/
get(key, defaultValue = '')
{
return this.assets[ key ] || this.assets[ this.fixKey(key) ] || defaultValue;
}
/**
* Delete an item from the manifest.
*
* @param {string} key
* @return {boolean}
*/
delete(key)
{
if ( has(this.assets, key) ) {
return (delete this.assets[ key ]);
}
key = this.fixKey(key);
if ( has(this.assets, key) ) {
return (delete this.assets[ key ]);
}
return false;
}
/**
* Process compilation assets.
*
* @param {object} assets - Assets by chunk name
* @return {object}
*/
processAssetsByChunkName(assets)
{
Object.keys(assets).forEach( chunkName => {
maybeArrayWrap( assets[ chunkName ] )
.filter( f => ! this.isHMR(f) ) // Remove hot module replacement files
.forEach( filename => {
this.assetNames.set( chunkName + this.getExtension( filename ), filename );
});
});
return this.assetNames;
}
/**
* Get the data for `JSON.stringify()`.
*
* @return {object}
*/
toJSON()
{
// This is the last chance to modify the data before the manifest file gets created.
return this.hooks.transform.call(this.assets, this);
}
/**
* `JSON.stringify()` the manifest.
*
* @return {string}
*/
toString()
{
return JSON.stringify(this, this.options.replacer, this.options.space) || '{}';
}
/**
* Merge data if the output file already exists
*/
maybeMerge()
{
if ( this.options.merge ) {
try {
this[ IS_MERGING ] = true;
const data = JSON.parse(fs.readFileSync(this.getOutputPath()));
for ( const key in data ) {
if ( ! this.has(key) ) {
this.set(key, data[ key ]);
}
}
} catch (err) { // eslint-disable-line
} finally {
this[ IS_MERGING ] = false;
}
}
}
/**
* @param {object} entrypoints from a compilation
*/
getEntrypointFilesGroupedByExtension( entrypoints )
{
const files = Object.create(null);
const removeHMR = f => ! this.isHMR(f);
const groupFilesByExtension = (files, file) => {
const ext = this.getExtension(file).replace(/^\.+/, '').toLowerCase();
files[ ext ] = files[ ext ] || [];
files[ ext ].push( this.getPublicPath( file ) );
return files;
};
for ( const [ name, entrypoint ] of entrypoints ) {
files[ name ] = entrypoint
.getFiles()
.filter( removeHMR )
.reduce( groupFilesByExtension, Object.create(null) );
}
return files;
}
/**
* Handle the `emit` event
*
* @param {object} compilation - the Webpack compilation object
* @param {Function} callback
*/
handleEmit(compilation, callback)
{
this.stats = compilation.getStats().toJson({
all: false,
assets: true,
});
this.processAssetsByChunkName( this.stats.assetsByChunkName );
for ( const [ filename, hashedFile ] of this.assetNames ) {
this.currentAsset = compilation.assets[ hashedFile ];
// `integrity` may have already been set by another plugin, like `webpack-subresource-integrity`.
// Only generate the SRI hash if `integrity` is not found.
if ( this.options.integrity && this.currentAsset && ! this.currentAsset[ this.options.integrityPropertyName ] ) {
this.currentAsset[ this.options.integrityPropertyName ] = getSRIHash( this.options.integrityHashes, this.currentAsset.source() );
}
this.set( filename, hashedFile );
this.currentAsset = null;
}
if ( this.options.entrypoints ) {
const entrypoints = this.getEntrypointFilesGroupedByExtension( compilation.entrypoints );
if ( this.options.entrypointsKey === false ) {
for ( const key in entrypoints ) {
this.setRaw( key, entrypoints[ key ] );
}
} else {
this.setRaw( this.options.entrypointsKey, entrypoints );
}
}
this.maybeMerge();
const output = this.getManifestPath(
compilation,
this.inDevServer() ?
path.basename( this.getOutputPath() ) :
path.relative( compilation.compiler.outputPath, this.getOutputPath() )
);
compilation.assets[ output ] = new RawSource(this.toString());
callback();
}
/**
* Get the parsed output path. [hash] is supported.
*
* @param {object} compilation - the Webpack compilation object
* @param {string} filename
* @return {string}
*/
getManifestPath(compilation, filename)
{
return compilation.getPath( filename, { chunk: { name: 'manifest' }, filename: 'manifest.json' } );
}
/**
* Write to disk using `fs`.
*
* This is likely only needed if you're using webpack-dev-server
* and you don't want to keep the manifest file only in memory.
*
* @param {object} compilation - the Webpack compilation object
*/
handleAfterEmit(compilation)
{
// Reset the internal mapping of original name to hashed name after every compilation.
this.assetNames.clear();
if ( ! this.options.writeToDisk ) {
return Promise.resolve();
}
return new Promise( (resolve, reject) => {
const output = this.getManifestPath( compilation, this.getOutputPath() );
require('mkdirp')(path.dirname(output))
.then(() => fs.writeFile( output, this.toString(), resolve ))
.catch(reject);
});
}
/**
* Record asset names
*
* @param {object} loaderContext
* @param {object} module
*/
handleNormalModuleLoader(loaderContext, module)
{
const { emitFile } = loaderContext;
// Webpack 5 added the assetInfo argument.
// Capture all args so it'll work in Webpack 4+.
loaderContext.emitFile = (...args) => {
const [ name ] = args;
const originalName = path.join(
path.dirname(name),
path.basename(module.userRequest)
);
// ignore emitFile calls from mini-css-extract-plugin
// https://github.com/webpack-contrib/mini-css-extract-plugin/pull/177
if (!module.identifier().includes('/mini-css-extract-plugin/')) {
this.assetNames.set(originalName, name);
}
return emitFile.apply(module, args);
};
}
/**
* Hook into the compilation object
*
* @param {object} compilation - the Webpack compilation object
*/
handleCompilation(compilation)
{
compilation.hooks.normalModuleLoader.tap(PLUGIN_NAME, this.handleNormalModuleLoader.bind(this));
}
/**
* Determine if webpack-dev-server is being used
*
* @return {boolean}
*/
inDevServer()
{
if ( process.argv.some( arg => arg.includes('webpack-dev-server') ) ) {
return true;
}
return has(this, 'compiler.outputFileSystem') && this.compiler.outputFileSystem.constructor.name === 'MemoryFileSystem';
}
/**
* Get the file system path to the manifest
*
* @return {string} path to manifest file
*/
getOutputPath()
{
if ( ! this.compiler ) {
return '';
}
if ( path.isAbsolute( this.options.output ) ) {
return this.options.output;
}
if ( this.inDevServer() ) {
let outputPath = get( this, 'compiler.options.devServer.outputPath', get( this, 'compiler.outputPath', '/' ) );
if ( outputPath === '/' ) {
warn.once('Please use an absolute path in options.output when using webpack-dev-server.');
outputPath = get( this, 'compiler.context', process.cwd() );
}
return path.resolve( outputPath, this.options.output );
}
return path.resolve( this.compiler.outputPath, this.options.output );
}
/**
* Get the public path for the filename
*
* @param {string} filePath
*/
getPublicPath(filename)
{
if ( typeof filename === 'string' ) {
const { publicPath } = this.options;
if ( typeof publicPath === 'function' ) {
return publicPath( filename, this );
}
if ( typeof publicPath === 'string' ) {
return url.resolve( publicPath, filename );
}
if ( publicPath === true ) {
return url.resolve(
get( this, 'compiler.options.output.publicPath', '' ),
filename
);
}
}
return filename;
}
/**
* Get a {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler|Proxy} for the manifest.
* This allows you to use `[]` to manage entries.
*
* @param {boolean} raw - Should the proxy use `setRaw` instead of `set`?
* @return {Proxy}
*/
getProxy(raw = false)
{
const setMethod = raw ? 'setRaw' : 'set';
return new Proxy(this, {
has(target, property) {
return target.has(property);
},
get(target, property) {
return target.get(property) || undefined;
},
set(target, property, value) {
return target[ setMethod ](property, value).has(property);
},
deleteProperty(target, property) {
return target.delete(property);
},
});
}
}
module.exports = WebpackAssetsManifest;