-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwebpackConfigurator.ts
1855 lines (1770 loc) · 70.2 KB
/
webpackConfigurator.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
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
// #!/usr/bin/env babel-node
// -*- coding: utf-8 -*-
/** @module webpackConfigurator */
'use strict'
/* !
region header
Copyright Torben Sickert (info["~at~"]torben.website) 16.12.2012
License
-------
This library written by Torben Sickert stand under a creative commons
naming 3.0 unported license.
See https://creativecommons.org/licenses/by/3.0/deed.de
endregion
*/
// region imports
import {
convertToValidVariableName,
evaluate,
EvaluationResult,
escapeRegularExpressions,
extend,
isFileSync,
isObject,
isPlainObject,
Mapping,
mask,
PlainObject,
PositiveEvaluationResult,
RecursivePartial,
represent,
Unpacked
} from 'clientnode'
import {
PluginOptions as ImageMinimizerOptions
} from 'image-minimizer-webpack-plugin'
import {extname, join, relative, resolve} from 'path'
import {Transformer as PostcssTransformer} from 'postcss'
import PostcssNode from 'postcss/lib/node'
import util from 'util'
import {
Chunk,
Compiler,
Compilation,
ContextReplacementPlugin,
DefinePlugin,
HotModuleReplacementPlugin,
IgnorePlugin,
NormalModuleReplacementPlugin,
ProvidePlugin,
RuleSetRule,
sources
} from 'webpack'
import {RawSource as WebpackRawSource} from 'webpack-sources'
import {
InjectManifestOptions as WorkboxInjectManifestOptions
} from 'workbox-build'
import getConfiguration from './configurator'
import {LoaderConfiguration as EJSLoaderConfiguration} from './ejsLoader'
import {
determineAssetType,
determineExternalRequest,
determineModuleFilePath,
getClosestPackageDescriptor,
isFilePathInLocation,
normalizePaths,
stripLoader
} from './helper'
import InPlaceAssetsIntoHTML from './plugins/InPlaceAssetsIntoHTML'
import HTMLTransformation from './plugins/HTMLTransformation'
import {
AdditionalLoaderConfiguration,
AssetPathConfiguration,
EvaluationScope,
GenericLoader,
HTMLConfiguration,
IgnorePattern,
InPlaceConfiguration,
Loader,
PackageDescriptor,
RedundantRequest,
ResolvedConfiguration,
RuleSet,
WebpackConfiguration,
WebpackExtendedResolveData,
WebpackLoader,
WebpackLoaderConfiguration,
WebpackLoaderIndicator,
WebpackPlugin,
WebpackPlugins,
WebpackResolveData
} from './type'
/// region optional imports
// NOTE: Has to be defined here to ensure to resolve from here.
const currentRequire: null | typeof require =
/*
typeof __non_webpack_require__ === 'function' ?
__non_webpack_require__ :
*/
eval(`typeof require === 'undefined' ? null : require`) as
null | typeof require
export const optionalRequire = <T = unknown>(id: string): null | T => {
try {
return currentRequire ? currentRequire(id) as T : null
} catch {
return null
}
}
const postcssCSSnano: null | typeof import('cssnano') =
optionalRequire<typeof import('cssnano')>('cssnano')
const postcssFontpath =
optionalRequire<typeof import('postcss-fontpath').default>(
'postcss-fontpath'
)
const postcssImport =
optionalRequire<typeof import('postcss-import')>('postcss-import')
const postcssSprites =
optionalRequire<typeof import('postcss-sprites').default>(
'postcss-sprites'
)
type UpdateRule = (
_node: PostcssNode, _token: PostcssNode, _image: Mapping<unknown>
) => void
const updateRule: undefined | UpdateRule =
optionalRequire<{updateRule: UpdateRule}>(
'postcss-sprites/lib/core'
)?.updateRule
const postcssURL =
optionalRequire<typeof import('postcss-url')>('postcss-url')
/// endregion
const pluginNameResourceMapping: Mapping = {
Favicon: 'favicons-webpack-plugin',
ImageMinimizer: 'image-minimizer-webpack-plugin',
HTML: 'html-webpack-plugin',
MiniCSSExtract: 'mini-css-extract-plugin',
offline: 'workbox-webpack-plugin',
Terser: 'terser-webpack-plugin'
}
const plugins: WebpackPlugins = {}
for (const [name, alias] of Object.entries(pluginNameResourceMapping)) {
const plugin: null | WebpackPlugin = optionalRequire(alias)
if (plugin)
plugins[name] = plugin
else
console.debug(`Optional webpack plugin "${name}" not available.`)
}
// endregion
const configuration: ResolvedConfiguration = getConfiguration()
const module: ResolvedConfiguration['module'] = configuration.module
// region initialisation
/// region determine library name
let libraryName: Array<string> | string | undefined
if (configuration.libraryName)
libraryName = configuration.libraryName
else if (Object.keys(configuration.injection.entry.normalized).length > 1)
libraryName = '[name]'
else {
libraryName = configuration.name
if (['assign', 'global', 'this', 'var', 'window'].includes(
configuration.exportFormat.self
))
libraryName = convertToValidVariableName(libraryName)
}
if (libraryName === '*')
libraryName = ['assign', 'global', 'this', 'var', 'window'].includes(
configuration.exportFormat.self
) ?
Object.keys(
configuration.injection.entry.normalized
).map((name: string): string => convertToValidVariableName(name)) :
undefined
/// endregion
/// region plugins
const pluginInstances: WebpackConfiguration['plugins'] = []
//// region define modules to ignore
for (const pattern of ([] as Array<IgnorePattern>).concat(
configuration.injection.ignorePattern
)) {
if (typeof (pattern as {contextRegExp: string}).contextRegExp === 'string')
(pattern as {contextRegExp: RegExp}).contextRegExp =
new RegExp((pattern as {contextRegExp: string}).contextRegExp)
if (
typeof (pattern as {resourceRegExp: string}).resourceRegExp ===
'string'
)
(pattern as {resourceRegExp: RegExp}).resourceRegExp =
new RegExp((pattern as {resourceRegExp: string}).resourceRegExp)
pluginInstances.push(new IgnorePlugin(pattern as IgnorePlugin['options']))
}
//// endregion
//// region define modules to replace
for (const [source, replacement] of Object.entries(
module.replacements.normal
)) {
const search = new RegExp(source)
pluginInstances.push(new NormalModuleReplacementPlugin(
search,
(resource: {request: string}): void => {
resource.request = resource.request.replace(search, replacement)
}
))
}
//// endregion
//// region generate html file
let htmlAvailable = false
if (plugins.HTML)
for (const htmlConfiguration of configuration.files.html)
if (isFileSync(htmlConfiguration.template.filePath)) {
pluginInstances.push(new plugins.HTML({
...htmlConfiguration,
template: htmlConfiguration.template.request
}))
htmlAvailable = true
}
//// endregion
//// region generate favicons
if (
htmlAvailable &&
Object.prototype.hasOwnProperty.call(configuration, 'favicon') &&
plugins.Favicon &&
isFileSync(([] as Array<string>).concat(configuration.favicon.logo)[0])
)
pluginInstances.push(new plugins.Favicon(configuration.favicon))
//// endregion
//// region provide offline functionality
if (
htmlAvailable &&
configuration.offline &&
Object.prototype.hasOwnProperty.call(plugins, 'offline')
) {
if (!['serve', 'test:browser'].includes(
configuration.givenCommandLineArguments[2]
))
for (const [name, extension] of Object.entries({
cascadingStyleSheet: 'css',
javaScript: 'js'
})) {
const type: keyof InPlaceConfiguration =
name as keyof InPlaceConfiguration
if (configuration.inPlace[type]) {
const matches: Array<string> =
Object.keys(configuration.inPlace[type])
if (!Array.isArray(configuration.offline.common.excludeChunks))
configuration.offline.common.excludeChunks = []
for (const name of matches)
configuration.offline.common.excludeChunks.push(
relative(
configuration.path.target.base,
configuration.path.target.asset[
type as keyof AssetPathConfiguration
]
) +
`${name}.${extension}?${configuration.hashAlgorithm}=*`
)
}
}
if (plugins.offline) {
if (
([] as Array<string>)
.concat(configuration.offline.use)
.includes('injectionManifest')
)
pluginInstances.push(new plugins.offline.InjectManifest(
extend<WorkboxInjectManifestOptions>(
true,
configuration.offline.common,
configuration.offline.injectionManifest
)
))
if (
([] as Array<string>)
.concat(configuration.offline.use)
.includes('generateServiceWorker')
)
pluginInstances.push(new plugins.offline.GenerateSW(extend(
true,
configuration.offline.common,
configuration.offline.generateServiceWorker
)))
}
}
//// endregion
//// region provide build environment
if (Object.prototype.hasOwnProperty.call(
configuration.buildContext, 'definitions'
))
pluginInstances.push(
new DefinePlugin(configuration.buildContext.definitions)
)
if (module.provide)
pluginInstances.push(new ProvidePlugin(module.provide))
//// endregion
//// region modules/assets
///// region apply module pattern
pluginInstances.push({apply: (compiler: Compiler): void => {
const name = 'ApplyModulePattern'
compiler.hooks.compilation.tap(
name,
(compilation: Compilation): void => {
compilation.hooks.processAssets.tap(
{
name,
additionalAssets: true,
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
},
(assets): void => {
for (const [request, asset] of Object.entries(assets)) {
const filePath: string = request.replace(/\?[^?]+$/, '')
const type: null | string = determineAssetType(
filePath,
configuration.buildContext.types,
configuration.path
)
if (
type &&
Object.prototype.hasOwnProperty.call(
configuration.assetPattern, type
) &&
(new RegExp(
configuration.assetPattern[type]
.includeFilePathRegularExpression
)).test(filePath) &&
!(new RegExp(
configuration.assetPattern[type]
.excludeFilePathRegularExpression
)).test(filePath)
) {
const source: Buffer | string = asset.source()
if (typeof source === 'string')
compilation.assets[request] =
new WebpackRawSource(
configuration.assetPattern[type]
.pattern.replace(
/\{1\}/g,
source.replace(/\$/g, '$$$')
)
) as unknown as sources.Source
}
}
}
)
}
)
}})
///// endregion
///// region in-place configured assets in the main html file
/*
TODO
/
NOTE: We have to translate template delimiter to html compatible
sequences and translate it back later to avoid unexpected escape
sequences in resulting html.
/
const window: DOMWindow = (new DOM(
content
.replace(/<%/g, '##+#+#+##')
.replace(/%>/g, '##-#-#-##')
)).window
->
.replace(/##\+#\+#\+##/g, '<%')
.replace(/##-#-#-##/g, '%>')
*/
if (
plugins.HTML &&
htmlAvailable &&
!['serve', 'test:browser']
.includes(configuration.givenCommandLineArguments[2]) &&
configuration.inPlace.cascadingStyleSheet &&
Object.keys(configuration.inPlace.cascadingStyleSheet).length ||
configuration.inPlace.javaScript &&
Object.keys(configuration.inPlace.javaScript).length
)
pluginInstances.push(new InPlaceAssetsIntoHTML({
cascadingStyleSheet: configuration.inPlace.cascadingStyleSheet,
javaScript: configuration.inPlace.javaScript,
htmlPlugin: plugins.HTML
}))
///// endregion
///// region mark empty javaScript modules as dummy
if (!(
configuration.needed.javaScript ||
configuration.needed.javaScriptExtension ||
configuration.needed.typeScript ||
configuration.needed.typeScriptExtension
))
configuration.files.compose.javaScript = resolve(
configuration.path.target.asset.javaScript, '.__dummy__.compiled.js'
)
///// endregion
///// region extract cascading style sheets
const cssOutputPath: string | ((_asset: unknown) => string) =
configuration.files.compose.cascadingStyleSheet
if (cssOutputPath && plugins.MiniCSSExtract)
pluginInstances.push(new plugins.MiniCSSExtract({
filename: typeof cssOutputPath === 'string' ?
relative(configuration.path.target.base, cssOutputPath) :
cssOutputPath
}))
///// endregion
///// region performs implicit external logic
if (configuration.injection.external.modules === '__implicit__')
/*
We only want to process modules from local context in library mode,
since a concrete project using this library should combine all assets
(and de-duplicate them) for optimal bundling results.
NOTE: Only native javascript and json modules will be marked as
external dependency.
*/
configuration.injection.external.modules = (
{context, request},
callback: (
error?: Error,
result?: Array<string> | boolean | string | Mapping<unknown>,
type?: string
) => void
): void => {
if (typeof request !== 'string') {
callback()
return
}
request = request.replace(/^!+/, '')
if (request.startsWith('/'))
request = relative(configuration.path.context, request)
for (const filePath of module.directoryNames)
if (request.startsWith(filePath)) {
request = request.substring(filePath.length)
if (request.startsWith('/'))
request = request.substring(1)
break
}
// region pattern based aliasing
const filePath: null | string = determineModuleFilePath(
request,
{},
{},
{file: configuration.extensions.file.external},
configuration.path.context,
context,
configuration.path.ignore,
module.directoryNames,
configuration.package.main.fileNames,
configuration.package.main.propertyNames,
configuration.package.aliasPropertyNames,
configuration.encoding
)
if (filePath)
for (const [pattern, targetConfiguration] of Object.entries(
configuration.injection.external.aliases
))
if (targetConfiguration && pattern.startsWith('^')) {
const regularExpression = new RegExp(pattern)
if (regularExpression.test(filePath)) {
let match = false
const firstKey = Object.keys(targetConfiguration)[0]
let target: string =
(targetConfiguration as Mapping)[firstKey]
if (typeof target !== 'string')
break
const replacementRegularExpression =
new RegExp(firstKey)
if (target.startsWith('?')) {
target = target.substring(1)
const aliasedRequest: string = request.replace(
replacementRegularExpression, target)
if (aliasedRequest !== request)
match = Boolean(determineModuleFilePath(
aliasedRequest,
{},
{},
{
file: configuration.extensions.file
.external
},
configuration.path.context,
context,
configuration.path.ignore,
module.directoryNames,
configuration.package.main.fileNames,
configuration.package.main.propertyNames,
configuration.package.aliasPropertyNames,
configuration.encoding
))
} else
match = true
if (match) {
request = request.replace(
replacementRegularExpression, target
)
break
}
}
}
// endregion
const resolvedRequest: null | string = determineExternalRequest(
request,
configuration.path.context,
context,
configuration.injection.entry.normalized,
module.directoryNames,
module.aliases,
module.replacements.normal,
configuration.extensions,
configuration.path.source.asset.base,
configuration.path.ignore,
module.directoryNames,
configuration.package.main.fileNames,
configuration.package.main.propertyNames,
configuration.package.aliasPropertyNames,
configuration.injection.external.implicit.pattern.include,
configuration.injection.external.implicit.pattern.exclude,
configuration.inPlace.externalLibrary.normal,
configuration.inPlace.externalLibrary.dynamic,
configuration.encoding
)
if (resolvedRequest) {
const keys: Array<string> = ['amd', 'commonjs', 'commonjs2', 'root']
let result: (Mapping & {root?: Array<string>}) | string =
resolvedRequest
if (Object.prototype.hasOwnProperty.call(
configuration.injection.external.aliases, request
)) {
// region normal alias replacement
result = {default: request}
if (
typeof configuration.injection.external.aliases[
request
] === 'string'
)
for (const key of keys)
result[key] = configuration.injection.external.aliases[
request
] as unknown as string
else if (
typeof configuration.injection.external.aliases[
request
] === 'function'
)
for (const key of keys)
result[key] = (
configuration.injection.external.aliases[
request
] as (_request: string, _key: string) => string
)(request, key)
else if (isObject(configuration.injection.external.aliases[
request
]))
extend<Mapping>(
result as Mapping,
configuration.injection.external.aliases[request] as
Mapping
)
if (Object.prototype.hasOwnProperty.call(result, 'default'))
for (const key of keys)
if (!Object.prototype.hasOwnProperty.call(result, key))
result[key] = result.default
// endregion
}
if (
typeof result !== 'string' &&
Object.prototype.hasOwnProperty.call(result, 'root') &&
Array.isArray(result.root)
)
result.root = ([] as Array<string>)
.concat(result.root)
.map((name: string): string =>
convertToValidVariableName(name)
)
const exportFormat: string =
Object.prototype.hasOwnProperty.call(
configuration.exportFormat, 'external'
) ?
configuration.exportFormat.external :
configuration.exportFormat.self
callback(
undefined,
(
exportFormat === 'umd' || typeof result === 'string' ?
result :
result[exportFormat]
) as Array<string> | boolean | string | Mapping<unknown>,
exportFormat
)
return
}
callback()
}
///// endregion
//// endregion
//// region apply final html modifications/fixes
if (htmlAvailable && plugins.HTML)
pluginInstances.push(new HTMLTransformation({
hashAlgorithm: configuration.hashAlgorithm,
htmlPlugin: plugins.HTML,
files: configuration.files.html
}))
//// endregion
//// region context replacements
for (const contextReplacement of module.replacements.context)
pluginInstances.push(new ContextReplacementPlugin(...(
contextReplacement.map((value: string): RegExp | string => {
const evaluated: EvaluationResult<RegExp | string> =
evaluate<RegExp | string>(
value, {configuration, __dirname, __filename}
)
if (evaluated.error)
throw new Error(
'Error occurred during processing given context ' +
`replacement: ${evaluated.error}`
)
return (evaluated as PositiveEvaluationResult<RegExp | string>)
.result
}) as [RegExp, string]
)))
//// endregion
//// region consolidate duplicated module requests
/*
NOTE: Redundancies usually occur when symlinks aren't converted to their
real paths since real paths can be de-duplicated by webpack but if two
linked modules share the same transitive dependency webpack wont recognize
them as same dependency.
*/
if (module.enforceDeduplication) {
const absoluteContextPath: string = resolve(configuration.path.context)
const consolidator = (result: WebpackExtendedResolveData): void => {
const targetPath: string = result.createData.resource
if (
targetPath &&
/((?: ^|\/)node_modules\/.+)/.test(targetPath) &&
(
!targetPath.startsWith(absoluteContextPath) ||
/((?: ^|\/)node_modules\/.+){2}/.test(targetPath)
) &&
isFileSync(targetPath)
) {
const packageDescriptor: null | PackageDescriptor =
getClosestPackageDescriptor(targetPath)
if (packageDescriptor) {
let pathPrefixes: Array<string>
let pathSuffix: string
if (targetPath.startsWith(absoluteContextPath)) {
const matches: null | RegExpMatchArray =
targetPath.match(/((?: ^|.*?\/)node_modules\/)/g)
if (matches === null)
return
pathPrefixes = Array.from(matches)
/*
Remove last one to avoid replacing with the already set
path.
*/
pathPrefixes.pop()
let index = 0
for (const pathPrefix of pathPrefixes) {
if (index > 0)
pathPrefixes[index] = resolve(
pathPrefixes[index - 1], pathPrefix
)
index += 1
}
pathSuffix = targetPath.replace(
/(?: ^|.*\/)node_modules\/(.+$)/, '$1'
)
} else {
pathPrefixes = [
resolve(absoluteContextPath, 'node_modules')
]
// Find longest common prefix.
let index = 0
while (
index < absoluteContextPath.length &&
absoluteContextPath.charAt(index) ===
targetPath.charAt(index)
)
index += 1
pathSuffix = targetPath
.substring(index)
.replace(/^.*\/node_modules\//, '')
}
let redundantRequest: null | RedundantRequest = null
for (const pathPrefix of pathPrefixes) {
const alternateTargetPath: string =
resolve(pathPrefix, pathSuffix)
if (isFileSync(alternateTargetPath)) {
const otherPackageDescriptor: null | PackageDescriptor =
getClosestPackageDescriptor(alternateTargetPath)
if (otherPackageDescriptor) {
if (
packageDescriptor.configuration.version ===
otherPackageDescriptor.configuration.version
) {
console.info(
'\nConsolidate module request "' +
`${targetPath}" to "` +
`${alternateTargetPath}".`
)
/*
NOTE: Only overwriting
"result.createData.resource" like
implemented in
"NormaleModuleReplacementPlugin" does
not always work.
*/
result.request =
result.createData.rawRequest =
result.createData.request =
result.createData.resource =
result.createData.userRequest =
alternateTargetPath
return
}
redundantRequest = {
path: alternateTargetPath,
version:
otherPackageDescriptor.configuration
.version
}
}
}
}
if (redundantRequest)
console.warn(
'\nIncluding different versions of same package "' +
`${packageDescriptor.configuration.name}". Module "` +
`${targetPath}" (version ` +
`${packageDescriptor.configuration.version}) has ` +
`redundancies with "${redundantRequest.path}" (` +
`version ${redundantRequest.version}).`
)
}
}
}
pluginInstances.push({apply: (compiler: Compiler) => {
compiler.hooks.normalModuleFactory.tap(
'WebOptimizerModuleConsolidation',
(nmf: ReturnType<Compiler['createNormalModuleFactory']>) => {
nmf.hooks.afterResolve.tap(
'WebOptimizerModuleConsolidation',
consolidator as (_result: WebpackResolveData) => void
)
}
)
}})
}
/*
new NormalModuleReplacementPlugin(
/.+/,
(result: {
context: string
createData: {resource: string}
request: string
}): void => {
const isResource: boolean = Boolean(result.createData.resource)
const targetPath: string = isResource ?
result.createData.resource :
resolve(result.context, result.request)
if (
targetPath &&
/((?: ^|\/)node_modules\/.+){2}/.test(targetPath) &&
isFileSync(targetPath)
) {
const packageDescriptor: null | PackageDescriptor =
Helper.getClosestPackageDescriptor(targetPath)
if (packageDescriptor) {
const pathPrefixes: null | RegExpMatchArray = targetPath.match(
/((?: ^|.*?\/)node_modules\/)/g
)
if (pathPrefixes === null)
return
// Avoid finding the same artefact.
pathPrefixes.pop()
let index: number = 0
for (const pathPrefix of pathPrefixes) {
if (index > 0)
pathPrefixes[index] =
resolve(pathPrefixes[index - 1], pathPrefix)
index += 1
}
const pathSuffix: string =
targetPath.replace(/(?: ^|.*\/)node_modules\/(.+$)/, '$1')
let redundantRequest: null | PlainObject = null
for (const pathPrefix of pathPrefixes) {
const alternateTargetPath: string =
resolve(pathPrefix, pathSuffix)
if (isFileSync(alternateTargetPath)) {
const otherPackageDescriptor: null | PackageDescriptor =
Helper.getClosestPackageDescriptor(
alternateTargetPath
)
if (otherPackageDescriptor) {
if (
packageDescriptor.configuration.version ===
otherPackageDescriptor.configuration.version
) {
console.info(
'\nConsolidate module request "' +
`${targetPath}" to "` +
`${alternateTargetPath}".`
)
result.createData.resource =
alternateTargetPath
result.request = alternateTargetPath
return
}
redundantRequest = {
path: alternateTargetPath,
version:
otherPackageDescriptor.configuration
.version
}
}
}
}
if (redundantRequest)
console.warn(
'\nIncluding different versions of same package "' +
`${packageDescriptor.configuration.name}". Module "` +
`${targetPath}" (version ` +
`${packageDescriptor.configuration.version}) has ` +
`redundancies with "${redundantRequest.path}" (` +
`version ${redundantRequest.version}).`
)
}
}
}
))*/
//// endregion
/// endregion
/// region loader helper
const isFilePathInDependencies = (filePath: string): boolean => {
filePath = stripLoader(filePath)
return isFilePathInLocation(
filePath,
configuration.path.ignore
.concat(module.directoryNames, configuration.loader.directoryNames)
.map((filePath: string): string =>
resolve(configuration.path.context, filePath)
)
.filter((filePath: string): boolean =>
!configuration.path.context.startsWith(filePath)
)
)
}
const loader: Loader = {} as unknown as Loader
const scope: EvaluationScope = {
configuration,
isFilePathInDependencies,
loader,
require: currentRequire ?? require
}
const evaluateAnThrow = <T = unknown>(
object: unknown, filePath: string = configuration.path.context
): T => {
if (typeof object === 'string') {
const evaluated: EvaluationResult<T> =
evaluate<T>(object, {filePath, ...scope})
if (evaluated.error)
throw new Error(
'Error occurred during processing given expression: ' +
evaluated.error
)
return (evaluated as PositiveEvaluationResult<T>).result
}
return object as T
}
const evaluateMapper =
<T = unknown>(value: unknown): T => evaluateAnThrow<T>(value)
const evaluateAdditionalLoaderConfiguration = (
loaderConfiguration: AdditionalLoaderConfiguration
): WebpackLoaderConfiguration => ({
exclude: (filePath: string): boolean =>
evaluateAnThrow<boolean>(loaderConfiguration.exclude, filePath),
include:
loaderConfiguration.include &&
evaluateAnThrow<WebpackLoaderIndicator>(loaderConfiguration.include) ||
configuration.path.source.base,
test: new RegExp(evaluateAnThrow<string>(loaderConfiguration.test)),
use: evaluateAnThrow<Array<WebpackLoader> | WebpackLoader>(
loaderConfiguration.use
)
})
const getIncludingPaths = (path: string): Array<string> =>
normalizePaths([path].concat(module.locations.directoryPaths))
const cssUse: RuleSet = module.preprocessor.cascadingStyleSheet.additional.pre
.map(evaluateMapper)
.concat(
{loader: module.style.loader, options: module.style.options || {}},
{
loader: module.cascadingStyleSheet.loader,
options: module.cascadingStyleSheet.options || {}
},
module.preprocessor.cascadingStyleSheet.loader ?
{
loader: module.preprocessor.cascadingStyleSheet.loader,
options: extend(
true,
optionalRequire('postcss') ?
{postcssOptions: {
/*
NOTE: Some plugins like "postcss-import" are
not yet ported to postcss 8. Let the final
consumer decide which distribution suites most.
*/
plugins: ([] as Array<PostcssTransformer>).concat(
postcssImport ?
postcssImport({
root: configuration.path.context
}) as unknown as PostcssTransformer :
[],
module.preprocessor
.cascadingStyleSheet.additional.plugins.pre
.map(evaluateMapper) as
Array<PostcssTransformer>,
/*
NOTE: Checking path doesn't work if fonts
are referenced in libraries provided in
another location than the project itself
like the "node_modules" folder.
*/
postcssFontpath ?
postcssFontpath({
checkPath: false,
formats: [
{ext: 'woff2', type: 'woff2'},
{ext: 'woff', type: 'woff'}
]
}) :
[],
postcssURL ?
postcssURL({url: 'rebase'}) as
unknown as
PostcssTransformer :
[],
postcssSprites ?
postcssSprites({
filterBy: (): Promise<void> =>
new Promise<void>((
resolve: () => void,
reject: () => void
) => {
(
configuration.files.compose
.image ?
resolve :