-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathAssetCompiler.js
More file actions
1806 lines (1527 loc) · 61.9 KB
/
AssetCompiler.js
File metadata and controls
1806 lines (1527 loc) · 61.9 KB
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path');
const { AsyncSeriesHook, AsyncSeriesWaterfallHook, SyncBailHook, SyncWaterfallHook } = require('tapable');
const Compiler = require('webpack/lib/Compiler');
const Compilation = require('webpack/lib/Compilation');
const Cache = require('webpack/lib/Cache');
const AssetParser = require('webpack/lib/asset/AssetParser');
const AssetGenerator = require('webpack/lib/asset/AssetGenerator');
//const JavascriptParser = require('webpack/lib/javascript/JavascriptParser');
//const JavascriptGenerator = require('webpack/lib/javascript/JavascriptGenerator');
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
ASSET_MODULE_TYPE,
ASSET_MODULE_TYPE_INLINE,
ASSET_MODULE_TYPE_SOURCE,
ASSET_MODULE_TYPE_RESOURCE,
} = require('webpack/lib//ModuleTypeConstants');
const { yellowBright, cyanBright, green, greenBright, yellow } = require('ansis');
const Config = require('../Common/Config');
const { baseUri, urlPathPrefix, cssLoaderName } = require('../Loader/Utils');
const { findRootIssuer } = require('../Common/CompilationHelpers');
const { isDir } = require('../Common/FileUtils');
const { parseVersion, compareVersions, getQueryParams, getQueryParam, hasQueryParam } = require('../Common/Helpers');
const createPersistentCache = require('./createPersistentCache')();
const CssExtractModule = require('./Modules/CssExtractModule');
const Option = require('./Option');
const PluginService = require('./PluginService');
const Collection = require('./Collection');
const Resolver = require('./Resolver');
const Snapshot = require('./Snapshot');
const UrlDependency = require('./UrlDependency');
const Asset = require('./Asset');
const AssetEntry = require('./AssetEntry');
const AssetResource = require('./AssetResource');
const AssetInline = require('./AssetInline');
const AssetTrash = require('./AssetTrash');
const VMScript = require('../Common/VMScript');
const Integrity = require('./Extras/Integrity');
const { compilationName, verbose } = require('./Messages/Info');
const { PluginError, afterEmitException } = require('./Messages/Exception');
const { outputWarning } = require('./Messages/Warnings');
const loaderPath = require.resolve('../Loader');
const LoaderFactory = require('../Loader/LoaderFactory');
const { pluginName } = Config.get();
/**
* The CSS loader.
*
* @type {{loader: string, ident: undefined, options: undefined, type: undefined}}
*/
const cssLoader = {
loader: require.resolve('../Loader/cssLoader.js'),
type: undefined,
options: undefined,
ident: undefined,
};
/** @typedef {import('webpack/declarations/WebpackOptions').Output} WebpackOutputOptions */
/** @typedef {import('webpack').Compiler} Compiler */
/** @typedef {import('webpack').Compilation} Compilation */
/** @typedef {import('webpack/lib/FileSystemInfo')} FileSystemInfo */
/** @typedef {import('webpack/lib/FileSystemInfo').Snapshot} FileSystemSnapshot */
/** @typedef {import('webpack').ChunkGraph} ChunkGraph */
/** @typedef {import('webpack').Chunk} Chunk */
/** @typedef {import('webpack').Module} Module */
/** @typedef {import('webpack').sources.Source} Source */
/** @typedef {import('webpack-sources').RawSource} RawSource */
/** @typedef {import('webpack').Configuration} Configuration */
/** @typedef {import('webpack').PathData} PathData */
/** @typedef {import('webpack').AssetInfo} AssetInfo */
/**
* @typedef {Module} PluginModuleMeta Meta information for module generated by the plugin.
* @property {boolean} isTemplate
* @property {boolean} isScript
* @property {boolean} isStyle
* @property {boolean} isImportedStyle
* @property {boolean} isLoaderImport
* @property {boolean} isDependencyUrl
*/
/**
* @typedef {Object} FileInfo
* @property {string} resource The resource file, including a query.
* @property {string|undefined} filename The output filename.
*/
/** @type {WeakMap<Compilation, HtmlBundlerPlugin.Hooks>} */
const compilationHooksMap = new WeakMap();
let HotUpdateChunk;
let RawSource;
class AssetCompiler {
static processAssetsPromises = [];
/** Whether the installed Webpack version < 5.96.0 */
IS_WEBPACK_VERSION_LOWER_5_96_0 = true;
/** @type {Array<Promise>} */
promises = [];
/** @type AssetEntryOptions The current entry point during dependency compilation. */
currentEntryPoint;
/** @type Set<Error> Buffered exceptions thrown in hooks. */
exceptions = new Set();
isSnapshotInitialized = false;
/** @type {Compilation} */
compilation = null;
/** @type {Option} The alias to pluginOption for 3rd party plugins */
option = null;
pluginOption = null;
pluginContext = {
compilation: null,
asset: null,
assetEntry: null,
assetInline: null,
assetResource: null,
assetTrash: null,
collection: null,
cssExtractModule: null,
resolver: null,
/** @type Option */
pluginOption: null,
urlDependency: null,
loaderDependency: null,
};
// data file => entry files, uses for watching changes in data file, then recompile entries where it used
dataFileEntryMap = new Map();
/** @type {FileSystem} */
fs = null;
/**
* @param {Compilation} compilation The compilation.
* @returns {HtmlBundlerPlugin.Hooks} The attached hooks.
*/
static getHooks(compilation) {
if (!(compilation instanceof Compilation)) {
throw new TypeError(`The 'compilation' argument must be an instance of Compilation`);
}
let hooks = compilationHooksMap.get(compilation);
if (hooks == null) {
hooks = {
// use a bail or waterfall hook when the hook returns something
beforePreprocessor: new AsyncSeriesWaterfallHook(['content', 'loaderContext']),
preprocessor: new AsyncSeriesWaterfallHook(['content', 'loaderContext']),
// TODO: implement afterPreprocessor when will be required the feature
//afterPreprocessor: new AsyncSeriesWaterfallHook(['content', 'loaderContext']),
resolveSource: new SyncWaterfallHook(['source', 'info']),
postprocess: new AsyncSeriesWaterfallHook(['content', 'info']),
beforeEmit: new AsyncSeriesWaterfallHook(['content', 'entry']),
afterEmit: new AsyncSeriesHook(['entries']),
integrityHashes: new AsyncSeriesHook(['hashes']),
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
/**
* @param {PluginOptions|{}} options
*/
constructor(options = {}) {
this.pluginOption = new Option(this.pluginContext, { options, loaderPath: loaderPath });
this.option = this.pluginOption;
// TODO: refactor replace all usages this.pluginOption > this.pluginContext.pluginOption
this.pluginContext.pluginOption = this.pluginOption;
this.assetTrash = new AssetTrash({ compilation: this.compilation });
this.pluginContext.assetTrash = this.assetTrash;
this.collection = new Collection(this.pluginContext);
this.pluginContext.collection = this.collection;
this.asset = new Asset();
this.pluginContext.asset = this.asset;
this.assetInline = new AssetInline();
this.pluginContext.assetInline = this.assetInline;
this.assetEntry = new AssetEntry({ ...this.pluginContext, entryLibrary: this.pluginOption.getEntryLibrary() });
this.pluginContext.assetEntry = this.assetEntry;
this.resolver = new Resolver(this.pluginContext);
this.pluginContext.resolver = this.resolver;
this.cssExtractModule = new CssExtractModule(this.pluginContext);
this.pluginContext.cssExtractModule = this.cssExtractModule;
this.assetResource = new AssetResource(this.pluginContext);
this.pluginContext.assetResource = this.assetResource;
this.urlDependency = new UrlDependency(this.pluginContext);
this.pluginContext.urlDependency = this.urlDependency;
// bind the instance context for using these methods as references in Webpack hooks
this.compile = this.compile.bind(this);
this.invalidate = this.invalidate.bind(this);
this.afterEntry = this.afterEntry.bind(this);
this.beforeResolve = this.beforeResolve.bind(this);
this.afterResolve = this.afterResolve.bind(this);
this.beforeModule = this.beforeModule.bind(this);
this.afterCreateModule = this.afterCreateModule.bind(this);
this.beforeLoader = this.beforeLoader.bind(this);
this.afterBuildModule = this.afterBuildModule.bind(this);
this.renderManifest = this.renderManifest.bind(this);
this.processAssetsOptimizeSize = this.processAssetsOptimizeSize.bind(this);
this.processAssetsFinalAsync = this.processAssetsFinalAsync.bind(this);
this.filterAlternativeRequests = this.filterAlternativeRequests.bind(this);
this.afterEmit = this.afterEmit.bind(this);
this.done = this.done.bind(this);
this.shutdown = this.shutdown.bind(this);
this.watch = this.watch.bind(this);
}
/**
* Called when a compiler object is initialized.
* Abstract method should be overridden in an extended class.
*
* @api
*
* @param {Compiler} compiler The instance of the webpack compiler.
* @abstract
*/
init(compiler) {}
/**
* Add default loader for entry files.
*/
addLoader() {
const defaultLoader = {
test: this.pluginOption.get().test,
// ignore 'asset/source' with the '?raw' query
// see https://webpack.js.org/guides/asset-modules/#replacing-inline-loader-syntax
resourceQuery: { not: [/raw/] },
loader: loaderPath,
};
this.pluginOption.addLoader(defaultLoader);
}
/**
* Add the process to pipeline.
*
* @api The public method can be used in an extended plugin.
*
* @param {string} name The name of process. Currently supported only `postprocess` pipeline.
* @param {Function: (content: string) => string} fn The process function to modify the generated content.
*/
addProcess(name, fn) {
this.pluginOption.addProcess(name, fn);
}
/**
* Apply plugin.
*
* @param {Compiler} compiler
*/
apply(compiler) {
if (!this.pluginOption.isEnabled()) return;
const { webpack } = compiler;
HotUpdateChunk = webpack.HotUpdateChunk;
RawSource = webpack.sources.RawSource;
this.promises = [];
this.fs = compiler.inputFileSystem.fileSystem;
this.webpack = webpack;
LoaderFactory.init(compiler);
this.pluginContext.loaderDependency = LoaderFactory.createDependency(compiler);
this.assetEntry.setCompiler(compiler);
this.pluginOption.initWebpack(compiler);
this.assetResource.init(compiler);
this.init(compiler);
this.addLoader();
// must be called after all initialisations of the pluginOption
this.resolver.init({ fs: this.fs });
// initialize integrity plugin
this.integrityPlugin = new Integrity(this.pluginOption);
// clear caches for tests in serve/watch mode
this.assetEntry.clear();
this.assetInline.clear();
this.collection.clear();
this.resolver.clear();
this.dataFileEntryMap.clear();
Snapshot.clear();
PluginError.clear();
// let know the loader that the plugin is being used
// TODO: init by PluginIndex, for each instance create own PluginService instance for pluginOption
PluginService.init(compiler, this.pluginContext, AssetCompiler);
this.cacheDataComplete = false;
if (this.pluginOption.isCacheable()) {
const collectionCache = createPersistentCache(this.collection);
const cache = compiler.getCache(pluginName).getItemCache('PersistentCache', null);
compiler.hooks.beforeCompile.tapPromise(pluginName, () => {
return cache.getPromise().catch(() => {
this.collection.clear();
});
});
// Store before Webpack's disk cache shutdown task collects pending cache writes.
compiler.cache.hooks.shutdown.tap({ name: pluginName, stage: Cache.STAGE_DISK - 1 }, () => {
if (!this.cacheDataComplete) return;
const cacheData = collectionCache.getData();
cache.store(cacheData, (error) => {
if (error) {
throw new Error(error);
}
});
});
}
// entry option
this.assetEntry.init({
fs: this.fs,
});
compiler.hooks.watchRun.tap(pluginName, this.watch);
compiler.hooks.entryOption.tap(pluginName, this.afterEntry);
compiler.hooks.invalid.tap(pluginName, this.invalidate);
compiler.hooks.thisCompilation.tap(pluginName, this.compile);
compiler.hooks.afterEmit.tapPromise(pluginName, this.afterEmit);
compiler.hooks.done.tapPromise(pluginName, this.done);
compiler.hooks.shutdown.tap(pluginName, this.shutdown);
compiler.hooks.watchClose.tap(pluginName, this.shutdown);
// run integrity plugin
if (this.pluginOption.isIntegrityEnabled()) this.integrityPlugin.apply(compiler);
}
/**
* Called in watch mode after a new compilation is triggered
* but before the compilation is actually started.
*
* @param {Compiler} compiler
*/
watch(compiler) {
// create dependencies map of the entry templates by data file
if (this.dataFileEntryMap.size === 0) {
const pluginOption = this.pluginOption.get();
const globalData = pluginOption.data;
this.assetEntry.entriesById.forEach((item) => {
if (item.dataFile) {
this.dataFileEntryMap.set(item.dataFile, [item.sourceFile]);
}
});
if (typeof globalData === 'string') {
const revolvedDataFile = PluginService.resolveFile(compiler, globalData);
const entryFiles = Array.from(this.assetEntry.getEntryFiles());
this.dataFileEntryMap.set(revolvedDataFile, entryFiles);
}
}
// TODO: avoid double calling by multi-config
//console.log('===> hooks.watchRun.tap', { id: compiler.name });
this.pluginOption.initWatchMode();
PluginService.setWatchMode(compiler, true);
PluginService.watchRun(compiler);
}
/**
* Compile modules.
*
* @param {Compilation} compilation
* @param {NormalModuleFactory} normalModuleFactory
* @param {ContextModuleFactory} contextModuleFactory
*/
compile(compilation, { normalModuleFactory, contextModuleFactory }) {
const fs = this.fs;
const { NormalModule, Compilation } = compilation.compiler.webpack;
const normalModuleHooks = NormalModule.getCompilationHooks(compilation);
const renderStage = this.pluginOption.getRenderStage();
this.cacheDataComplete = false;
this.IS_WEBPACK_VERSION_LOWER_5_96_0 = compareVersions(compilation.compiler.webpack.version, '<', '5.96.0');
this.compilation = compilation;
this.pluginContext.compilation = compilation;
this.assetEntry.setCompilation(compilation);
this.assetTrash.init(compilation);
this.cssExtractModule.init(compilation);
this.urlDependency.init({ compilation, fs });
this.collection.init({
hooks: AssetCompiler.getHooks(compilation),
});
// resolve modules
normalModuleFactory.hooks.beforeResolve.tap(pluginName, this.beforeResolve);
normalModuleFactory.hooks.afterResolve.tap(pluginName, this.afterResolve);
contextModuleFactory.hooks.alternativeRequests.tap(pluginName, this.filterAlternativeRequests);
// build modules
// createModuleClass requires v5.81+
normalModuleFactory.hooks.createModuleClass.for(JAVASCRIPT_MODULE_TYPE_AUTO).tap(pluginName, this.beforeModule);
normalModuleFactory.hooks.module.tap(pluginName, this.afterCreateModule);
compilation.hooks.buildModule.tap(pluginName, this.beforeBuildModule);
compilation.hooks.succeedModule.tap(pluginName, this.afterBuildModule);
// called when a module build has failed
compilation.hooks.failedModule.tap(pluginName, (module, error) => {
// TODO: collect errors
});
// TODO: avoid random index order
// compilation.hooks.beforeChunkIds.tap(pluginName, (chunks) => {
// for (const chunk of chunks) {
// if (chunk.name.startsWith('script')) {
// // TODO: sort chinks by index and rename chunk.name, chunk.runtime according index
// console.log(chunks);
// }
// }
// });
// called after the succeedModule hook but right before the execution of a loader
normalModuleHooks.loader.tap(pluginName, this.beforeLoader);
// render source code of modules
compilation.hooks.renderManifest.tap(pluginName, this.renderManifest);
// Notes:
// - the TerserPlugin creates a `.LICENSE.txt` file at the PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE stage
// - the integrity hash will be created at the next stage, therefore,
// the license file and the license banner must be removed before PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
compilation.hooks.processAssets.tap(
{ name: pluginName, stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1 },
this.processAssetsOptimizeSize
);
// after render module's sources
// only in the processAssets hook is possible to modify an asset content via async function
compilation.hooks.processAssets.tapPromise({ name: pluginName, stage: renderStage }, this.processAssetsFinalAsync);
// output asset info tags in console statistics
compilation.hooks.statsPrinter.tap(pluginName, (stats) => {
stats.hooks.print.for('asset.info.minimized').tap(pluginName, (minimized, { green, formatFlag }) => {
if (!minimized) {
return '';
}
if (!green || !formatFlag) {
return 'minimized';
}
return green(formatFlag('minimized'));
});
});
}
/* istanbul ignore next: this method is called in watch mode after changes */
/**
* Invalidate changed file.
* Called in serve/watch mode.
*
* Limitation: currently supports for change only a single file.
*
* TODO: add supports to add/remove many files.
* The problem: if added/removed many files,
* then webpack calls the 'invalid' hook many times, for each file separately.
* Research: find the hook, what called once, before the 'invalid' hook,
* to create the snapshot of files after change.
*
* @param {string} fileName The old filename before change.
* @param {Number|null} changeTime
*/
invalidate(fileName, changeTime) {
const fs = this.fs;
const entryDir = this.pluginOption.getEntryPath();
const isDirectory = isDir({ fs, file: fileName });
Snapshot.create();
if (this.dataFileEntryMap.has(fileName)) {
const entryFiles = this.dataFileEntryMap.get(fileName);
if (this.pluginOption.isVerbose()) {
console.log(yellowBright`Modified data file: ${cyanBright(fileName)}`);
}
for (const module of this.compilation.modules) {
const moduleResource = module.resource || '';
if (moduleResource && entryFiles.find((file) => file === moduleResource)) {
this.compilation.rebuildModule(module, (error) => {
if (this.pluginOption.isVerbose()) {
console.log(greenBright` -> Rebuild dependency: ${cyanBright(moduleResource)}`);
}
});
}
}
}
if (isDirectory === true) return;
const { actionType, newFileName, oldFileName } = Snapshot.detectFileChange();
const isScript = this.pluginOption.isScript(fileName);
const inCollection = this.collection.hasScript(fileName);
const isEntryFile = (file) => file && file.startsWith(entryDir) && this.pluginOption.isEntry(file);
// 1. Invalidate an entry template.
if (
this.pluginOption.isDynamicEntry() &&
(isEntryFile(fileName) || isEntryFile(oldFileName) || isEntryFile(newFileName))
) {
switch (actionType) {
case 'modify':
this.collection.disconnectEntry(fileName);
break;
case 'add':
this.assetEntry.addEntry(newFileName);
this.collection.disconnectEntry(newFileName);
break;
case 'rename':
this.assetEntry.deleteEntry(oldFileName);
this.assetEntry.addEntry(newFileName);
break;
case 'remove':
this.assetEntry.deleteEntry(oldFileName);
break;
default:
break;
}
return;
}
// 2. Invalidate a JavaScript file loaded in an entry template.
if (actionType && isScript) {
switch (actionType) {
case 'add':
// through
case 'rename':
const missingFiles = Snapshot.getMissingFiles();
const { modules } = this.compilation;
missingFiles.forEach((files, issuer) => {
const missingFile = Array.from(files).find((file) => newFileName.endsWith(file));
// if an already used js file was unlinked in html and then renamed
if (!missingFile) return;
for (const module of modules) {
// the same template can be in many modules
if (module.resource === issuer || module.resource === newFileName) {
// reset errors for an unresolved js file, because the file can be renamed
module._errors = [];
// after rename a js file, try to rebuild the module of the entry file where the js file was linked
this.compilation.rebuildModule(module, (error) => {
// after rebuild, remove the missing file to avoid double rebuilding by another exception
Snapshot.deleteMissingFile(issuer, missingFile);
this.assetEntry.deleteMissingFile(missingFile);
});
}
}
});
break;
case 'remove':
// do nothing
break;
default:
break;
}
if (inCollection && (actionType === 'remove' || actionType === 'rename')) {
this.assetEntry.deleteEntry(oldFileName);
}
return;
}
// 3. if a partial is changed then rebuild all entry templates,
// because we don't have the dependency graph of the partial on the main template
const isEntry = this.assetEntry.isEntryResource(fileName);
if (!isEntry) {
const dependency = PluginService.getDependencyInstance(this.compilation.compiler);
// dependency is null when no html entry defined and a style in entry was changed
if (dependency) {
const isFileWatchable = dependency.isFileWatchable(fileName);
const isTemplate = this.pluginOption.isEntry(fileName);
if (isTemplate || isFileWatchable) {
if (this.pluginOption.isVerbose()) {
console.log(yellowBright`Modified partial: ${cyanBright(fileName)}`);
}
for (const module of this.compilation.modules) {
const moduleResource = module.resource || '';
if (moduleResource && this.assetEntry.isEntryResource(moduleResource)) {
this.compilation.rebuildModule(module, (error) => {
if (error) {
// TODO: research the strange error - "Cannot read properties of undefined (reading 'state')"
// in node_modules/webpack/lib/util/AsyncQueue.js:196
}
if (this.pluginOption.isVerbose()) {
console.log(greenBright` -> Rebuild entrypoint: ${cyanBright(moduleResource)}`);
}
});
}
}
}
}
}
}
/**
* Called after the entry configuration from webpack options has been processed.
*
* @param {string} context The base directory, an absolute path, for resolving entry points and loaders from the configuration.
* @param {Object<name:string, entry: Object>} entries The webpack entries.
*/
afterEntry(context, entries) {
this.assetEntry.addEntries(entries);
}
/**
* Filter alternative requests.
*
* Entry files should not have alternative requests.
* If the template file contains require and is compiled with `compile` mode,
* then ContextModuleFactory generates additional needless request as the relative path without a query.
* Such 'alternative request' must be removed from compilation.
*
* @param {Array<{}>} requests
* @param {{}} options
* @return {Array|undefined} Returns only alternative requests not related to entry files.
*/
filterAlternativeRequests(requests, options) {
// skip the request required as 'asset/source' with the '?raw' resourceQuery
// see https://webpack.js.org/guides/asset-modules/#replacing-inline-loader-syntax
if (/\?raw/.test(options.resourceQuery)) return;
return requests.filter((item) => !this.pluginOption.isEntry(item.request));
}
/**
* Called when a new dependency request is encountered.
*
* @param {Object} resolveData
* @return {boolean|undefined} Return undefined to processing, false to ignore dependency.
*/
beforeResolve(resolveData) {
const { request, dependencyType } = resolveData;
const [file] = request.split('?', 1);
const entryId = this.assetEntry.resolveEntryId(resolveData);
/** @type PluginModuleMeta */
const meta = {
isTemplate: this.assetEntry.isEntryResource(file),
isScript: false,
isStyle: false,
isImportedStyle: false,
isParentLoaderImport: false,
isLoaderImport: dependencyType === 'loaderImport',
isDependencyUrl: dependencyType === 'url',
};
resolveData._bundlerPluginMeta = meta;
resolveData.entryId = entryId;
/* istanbul ignore next */
// prevent compilation of renamed or deleted entry point in serve/watch mode
if (this.pluginOption.isDynamicEntry() && this.assetEntry.isDeletedEntryFile(file)) {
for (const [entryName, entry] of this.compilation.entries) {
if (entry.dependencies[0]?.request === request) {
// delete the entry from compilation to prevent creation unused chunks
this.compilation.entries.delete(entryName);
}
}
return false;
}
if (meta.isDependencyUrl) {
this.urlDependency.resolve(resolveData);
}
}
/**
* Called after the request is resolved.
*
* @param {Object} resolveData
* @return {boolean|undefined} Return undefined to processing, false to ignore dependency.
*/
afterResolve(resolveData) {
const { request, contextInfo, dependencyType, createData, _bundlerPluginMeta: meta } = resolveData;
const { resource, type } = createData;
const [file] = resource.split('?', 1);
// note: the contextInfo.issuer is the filename w/o a query
const { issuer } = contextInfo;
// the filename with an extension is available only after resolve
meta.isStyle = this.pluginOption.isStyle(file);
meta.isCSSStyleSheet = this.isCSSStyleSheet(createData);
// skip modules loaded via importModule, data-URL
if (meta.isLoaderImport || meta.isCSSStyleSheet || request.startsWith('data:')) return;
if (issuer) {
// TODO: refactor into AssetInline
const isAssetModule = [
ASSET_MODULE_TYPE,
ASSET_MODULE_TYPE_INLINE,
ASSET_MODULE_TYPE_RESOURCE,
ASSET_MODULE_TYPE_SOURCE,
].includes(type);
if (isAssetModule) {
let encoding = 'base64'; // default encoding for all resources
let hasInlineQuery = getQueryParam(resource, 'inline') != null;
let isInlineSvg = false;
let svgOptions;
if (this.assetInline.isSvgFile(resource)) {
svgOptions = this.pluginOption.getInlineSvgOptions(resource, createData);
if (svgOptions?.warning) {
outputWarning(svgOptions.warning);
}
isInlineSvg = svgOptions.inline;
encoding = svgOptions?.encoding;
}
// query `?inline`
if (hasInlineQuery || isInlineSvg) {
this.setAssetModuleTypeInline(createData);
this.setAssetModuleEncoding(createData, encoding, hasInlineQuery, svgOptions);
}
}
// skip modules loaded in CSS via url()
if (meta.isDependencyUrl) return;
const isIssuerStyle = this.pluginOption.isStyle(issuer);
const parentModule = resolveData.dependencies[0]?._parentModule;
const { isLoaderImport } = parentModule?.resourceResolveData?._bundlerPluginMeta || {};
// skip the module loaded via importModule
if (isLoaderImport) {
meta.isParentLoaderImport = true;
return;
}
// exclude from compilation the css-loader runtime scripts for styles specified in HTML only,
// to avoid splitting the loader runtime scripts;
// allow runtime scripts for styles imported in JavaScript, regards deep imported styles via url()
if (isIssuerStyle && file.endsWith('.js')) {
const rootIssuer = findRootIssuer(this.compilation, issuer);
meta.isScript = true;
// return true if the root issuer is a JS (not style and not template), otherwise return false
return rootIssuer != null && !this.pluginOption.isStyle(rootIssuer) && !this.pluginOption.isEntry(rootIssuer);
}
// style loaded in *.vue file
if (request.includes('?vue&')) {
const { type } = Object.fromEntries(new URLSearchParams(request).entries());
if (type === 'style') {
meta.isStyle = true;
meta.isVueStyle = true;
}
}
// try to detect imported style as resolved resource file, because a request can be a node module w/o an extension
// the issuer can be a style if a scss contains like `@import 'main.css'`
if (!this.pluginOption.isStyle(issuer) && !this.pluginOption.isEntry(issuer) && meta.isStyle) {
const rootIssuer = findRootIssuer(this.compilation, issuer);
this.collection.importStyleRootIssuers.add(rootIssuer || issuer);
meta.isImportedStyle = true;
if (!createData.request.includes(cssLoader.loader)) {
// the request of an imported style must be different from the request for the same style specified in a html,
// otherwise webpack doesn't apply the added loader for the imported style,
// see the test case js-import-css-same-in-many4
createData.request = `${cssLoader.loader}!${createData.request}`;
if (meta.isVueStyle) {
createData.loaders = this.filterStyleLoaders(createData.loaders, parentModule.loaders);
} else {
createData.loaders = [cssLoader, ...createData.loaders];
}
}
}
}
meta.isScript = this.collection.hasScript(request);
}
/**
* Set data URL encoding for `asset/inline`.
*
* @param {Object} module
* @param {'base64' | false} encoding
* @param {boolean} hasInlineQuery
* @param {Object | null} svgOptions
*/
setAssetModuleEncoding(module, encoding, hasInlineQuery, svgOptions) {
if (this.IS_WEBPACK_VERSION_LOWER_5_96_0) {
// TODO: refactor into Exceptions
throw new Error(`\nThe support for the \`?inline\` query for assets is available since Webpack >= 5.96.`);
}
let assetEncoding = encoding === 'base64' ? 'base64' : false;
const moduleGraph = this.compilation.moduleGraph;
const moduleDataUrl = module.generator.dataUrlOptions;
const moduleDataUrlType = typeof moduleDataUrl;
const filename = module.generator.filename;
const publicPath = module.generator.publicPath;
const outputPath = module.generator.outputPath;
const emit = module.generator.emit;
const issuer = module.resourceResolveData?.context?.issuer;
const isIssuerScript = this.pluginOption.isScript(issuer || '');
let dataUrlOptions;
if (moduleDataUrlType === 'function') {
if (isIssuerScript) {
dataUrlOptions = (...args) => {
// extra processes SVG loaded in a JS file, because it will not be processed in renderManifest
let resultDataUrl = moduleDataUrl(...args);
let normalized = this.assetInline.normalizeDataUrlEncoding(resultDataUrl, svgOptions);
// TODO: research why is called double (perhaps the JS file (issuer) is called double)
// console.log(
// ' ====> INJECTION: ',
// { isIssuerScript, resource: module.resource, svgOptions, normalized },
// resultDataUrl,
// args
// );
return normalized.dataUrl;
};
} else {
dataUrlOptions = moduleDataUrl;
}
} else {
dataUrlOptions = moduleDataUrlType === 'object' ? { ...moduleDataUrl } : {};
dataUrlOptions.encoding = assetEncoding;
}
module.generator = new AssetGenerator(moduleGraph, dataUrlOptions, filename, publicPath, outputPath, emit);
}
/**
* Force set asset module type to `asset/inline`.
*
* @param {Object} module
*/
setAssetModuleTypeInline(module) {
module.type = ASSET_MODULE_TYPE_INLINE;
module.parser = new AssetParser(true);
}
/**
* Whether the module is imported CSSStyleSheet in JS.
*
* @param {{}} module
* @return {boolean}
*/
isCSSStyleSheet(module) {
return (
Array.isArray(module.loaders) &&
module?.loaders.some(
(loader) => loader.loader.includes('css-loader') && loader.options?.exportType === 'css-style-sheet'
)
);
}
/**
* Returns unique style loaders only.
*
* If a style file is imported in *.vue file then:
* - remove the needles vue loader
* - remove double loaders, occurs when using the lang="scss" attribute, e.g.: <style src="./style.scss" lang="scss">
*
* @param {Array<Object>} loaders The mishmash of loaders with duplicates.
* @param {Array<Object> | []} parentLoaders The issuer loaders.
* @return {Array<Object>} The style loaders.
*/
filterStyleLoaders(loaders, parentLoaders) {
const loaderRegExp = /([\\/]node_modules[\\/].+?[\\/])/;
const parentLoaderNames = [];
const uniqueStyleLoaders = new Map();
for (let { loader } of parentLoaders) {
let [loaderName] = loader.match(loaderRegExp);
if (loaderName) parentLoaderNames.push(loaderName);
}
// ignore endpoint (first) loader used by the issuer, e.g., when a style is imported in *.vue file, ignore vue loader
if (parentLoaderNames.find((name) => loaders[0].loader.includes(name))) {
loaders.shift();
}
for (let item of loaders) {
// skip duplicate loader
if (uniqueStyleLoaders.has(item.loader)) continue;
uniqueStyleLoaders.set(item.loader, item);
}
return [cssLoader, ...uniqueStyleLoaders.values()];
}
/**
* Called after the `createModule` hook and before the `module` hook.
*
* @param {Object} createData
* @param {Object} resolveData
*/
beforeModule(createData, resolveData) {
const { _bundlerPluginMeta: meta } = resolveData;
const query = createData.resourceResolveData?.query || '';
const isUrl = query.includes('url');
// lazy load CSS in JS using `?url` query, see js-import-css-lazy-url
if (meta.isImportedStyle && isUrl && !query.includes(cssLoaderName)) {
const filename = this.pluginOption.getCss().filename;
if (this.IS_WEBPACK_VERSION_LOWER_5_96_0) {
// Webpack <= 5.95
createData.generator = new AssetGenerator(undefined, filename);
} else {
// Webpack >= 5.96
const moduleGraph = this.compilation.moduleGraph;
const dataUrlOptions = undefined;
const publicPath = undefined;
const outputPath = undefined;
const emit = true;
createData.generator = new AssetGenerator(moduleGraph, dataUrlOptions, filename, publicPath, outputPath, emit);
}
createData.parser = new AssetParser(false);
createData.type = ASSET_MODULE_TYPE_RESOURCE;
}
}
/**
* Called after a module instance is created.
*
* @param {NormalModule} module The Webpack module.
* @param {Object} createData
* @param {Object} resolveData
*/
afterCreateModule(module, createData, resolveData) {
const { _bundlerPluginMeta: meta } = resolveData;
const { rawRequest, resource } = createData;
this.assetEntry.connectEntryAndModule(module, resolveData);
// skip the module loaded via importModule
if (meta.isLoaderImport || meta.isParentLoaderImport) return;
const { type, loaders } = module;
const { issuer } = resolveData.contextInfo;
// add missed scripts to compilation after deserialization
if (meta.isTemplate) {
if (this.collection.isDeserialized()) {
this.collection.addToCompilationDeserializedFiles(resource);
}
return;