-
Notifications
You must be signed in to change notification settings - Fork 0
/
SeperateChunkPlugin.js
1619 lines (1455 loc) · 60.9 KB
/
SeperateChunkPlugin.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
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
/*
Author Janzenzhang from Tencent
*/
var fs = require('fs');
var path = require('path');
var MODULE = require('module');
var PLATFORM = process.platform == 'darwin' ? 'MAC' : 'WIN';
var FILESLASH = PLATFORM == 'MAC' ? '/' : '\\';
var nextIdent = 0;
if (!console) {
console = {
log: function(a) {
return
}
}
}
// bundleFiles 该文件夹下的文件都需要打包在一起。
function SeperateChunkPlugin(options, filenameTemplate, selectedChunks, minChunks) {
if(options && typeof options === "object" && !Array.isArray(options)) {
this.chunkNames = options.name || options.names;
this.filenameTemplate = options.filename;
this.minChunks = options.minChunks;
this.selectedChunks = options.chunks;
if(options.children) this.selectedChunks = false;
this.async = options.async;
this.minSize = options.minSize;
this.outputScriptFile = options.outputScriptFile;
this.bundleFiles = options.bundleFiles;
} else {
var chunkNames = options;
if(typeof filenameTemplate !== "string" && filenameTemplate !== null) {
minChunks = selectedChunks;
selectedChunks = filenameTemplate;
filenameTemplate = chunkNames;
}
if(!Array.isArray(selectedChunks) && typeof selectedChunks !== "boolean" && selectedChunks !== null) {
minChunks = selectedChunks;
selectedChunks = undefined;
}
this.chunkNames = chunkNames;
this.filenameTemplate = filenameTemplate;
this.minChunks = minChunks;
this.selectedChunks = selectedChunks;
}
this.ident = __filename + (nextIdent++);
}
//正式开始拆分
function SeperateChunksInit(chunks, commonChunks, bundleFiles, outputScriptFile, compilation, compiler) {
var parentChunk = commonChunks[0], // 指定webpack模块初始化器。
allModules = getAllModulesExceptEnsure(chunks),
entries = getModuleRelativePathObjWithoutType(compilation.entries),
pathModObj = getModuleRelativePathObjWithoutType(allModules),
modResToMod = getModResToMod(allModules),
extraModObj = {},
originChunks = [],
config, key;
bundleFiles = testBundleFiles(bundleFiles);
chunks = removeExtraModuleWeDontNeed(chunks, getAllDependenciesRes(compilation), extraModObj);
chunks.forEach(function(chunk) {
originChunks.push(chunk);
})
//没有配置文件的情况下要自动生成配置文件
if (getConfig()) {
config = getConfig();
} else {
config = generateConfig(chunks, commonChunks, entries, bundleFiles);
}
if (PLATFORM == 'WIN') {
config = parseConfigIntoLocalStyle(config);
}
//判断config结构,并且根据情况会修改config的内容
if (testConfig(config)) {
seperateChunksByConfig.call(this, chunks, config, commonChunks, entries);
writeConfigToFile(config);
} else {
return false
}
//做一个转换,以后可能有更多功能
function testBundleFiles(bundleFiles) {
var newBundleFiles = bundleFiles;
if (typeof bundleFiles == 'string') {
newBundleFiles = [bundleFiles];
}
if (typeof bundleFiles == 'undefined') {
newBundleFiles = [];
}
return newBundleFiles
}
/**
* 通过对比dependenice和config,找到config中有的,而dependencies没有的。
* 把webpack偷偷装的模块去除(比如node-libs-browser中的)
*/
function removeExtraModuleWeDontNeed(chunks, dependencies, extraModObj) {
var extraPath,
extraModuleInstalledByWebpackSecretly = [],
pathModObj, modRes;
chunks.forEach(function(chunk) {
pathModObj = getModuleRelativePathObjWithoutType(chunk.modules);
for (modRes in pathModObj) {
if (!in_array(getModuleResource(pathModObj[modRes]), dependencies) && chunk.initial == true) {
extraModuleInstalledByWebpackSecretly.push(pathModObj[modRes].resource);
}
}
})
chunks.forEach(function(chunk) {
chunk.modules.forEach(function(mod) {
extraModuleInstalledByWebpackSecretly.forEach(function(extraPath) {
if (extraPath == mod.resource) {
mod.removeChunk(chunk);
extraModObj[mod.resource] = mod;
}
})
})
})
return chunks
}
function reinstallExtraModuleToEntry(entrychunk, extraModObj) {
var modRes;
for (modRes in extraModObj) {
extraModObj[modRes].addChunk(entrychunk);
entrychunk.addModule(extraModObj[modRes]);
}
}
/*
* 根据config来修改最后的chunks
*/
function seperateChunksByConfig(chunks, config, commonChunks, entries) {
var parentChunks = [],
newChunkName,
targetModules,
entryName,
parentChunk,
findEntryObj,
parentsChunkObj = {},
parentsChunkNameArr,
entryChunkNamesArr,
parentsChunkNameObj,
_this = this,
chunkNameObj,
parentChunkName,
chunkname,
BelongChunksToEntryChunk;
findEntryObj = findParents(config, entries, commonChunks[0]);
entryChunkNamesArr = findEntryObj.entriesNamesArr;
parentsChunkNameObj = findEntryObj.parentsChunkNameObj;
parentsChunkNameArr = findEntryObj.parentsChunkNameArr;
BelongChunksToEntryChunk = findEntryObj.BelongChunksToEntryChunk;
//先把现有的chunk里面的module都移除
removeAllChunksModule(allModules, originChunks);
//先把作为parent的chunk generate出来
parentsChunkNameArr.forEach(function(newChunkName) {
var newChunk;
targetModules = [];
config[newChunkName].forEach(function(moduleName) {
targetModules.push(modResToMod[addProjectPath(moduleName)]);
})
newChunk = generateChunk.call(_this, newChunkName, targetModules, !!in_array(newChunkName, parentsChunkNameArr), chunks, []);
parentsChunkObj[newChunkName] = newChunk;
})
// 把移除的module再次添加到chunk中
for (parentChunk in parentsChunkObj) {
reinstallExtraModuleToEntry(parentsChunkObj[parentChunk], extraModObj);
}
//再generate 剩余的chunk
for (newChunkName in config) {
if (!in_array(newChunkName, parentsChunkNameArr)) {
targetModules = [];
config[newChunkName].forEach(function(moduleName) {
targetModules.push(modResToMod[addProjectPath(moduleName)]);
})
generateChunk.call(_this, newChunkName, targetModules, !!in_array(newChunkName, parentsChunkNameArr), chunks, [parentsChunkObj[parentsChunkNameObj[newChunkName]]]);
}
}
chunkNameObj = getchunkNameObj(chunks);
/**
* 往parent chunks 添加各自入口chunks
* 比如:
* a.parent = c
* b.parent = c
* c.chunks = [a, b]
* 所以这里要把parentchunk 添加上chunks
*/
parentsChunkNameArr.forEach(function(parentChunkName) { // parentChunkName = common
for (chunkname in parentsChunkNameObj) {// chunkname = MyButton
if (parentsChunkNameObj[chunkname] == parentChunkName) {
if (chunkNameObj[parentChunkName].chunks.indexOf(chunkNameObj[chunkname]) < 0) {//防止重复添加
chunkNameObj[parentChunkName].addChunk(chunkNameObj[chunkname]);
}
}
}
})
/**
* 去重每一个chunk下的chunks
*/
// for (chunkname in chunks) {
// chunks[chunkname].chunks = removeDupicatesOfObj(chunks[chunkname].chunks);
// }
//设置异步chunk的parent的
chunks.forEach(function(asyncChunk) {
var parentNameArr = [];
if (asyncChunk.initial == false) {
asyncChunk.parents.forEach(function(parentchunk) {
parentchunk.chunks.push(asyncChunk);
})
}
})
//移除所有空的chunk
removeAllEmptyChunk(chunks);
generateScript(chunks, outputScriptFile, BelongChunksToEntryChunk, parentsChunkNameArr);
}
// 先把现有的chunk里面的module都移除
function removeAllChunksModule(allModules, originChunks) {
allModules.forEach(function(module) {
originChunks.forEach(function(chunk) {
module.removeChunk(chunk);
})
})
}
// 把所有的module的内容
function setModResource(allModules) {
compiler.options.resolve.extensions.forEach(function(ext) {
if (ext && !MODULE._extensions[ext]) {
MODULE._extensions[ext] = function() {
//空的 因为module._findPath需要遍历后缀,然后才能找到没有带后缀的文件。
}
}
});
allModules.forEach(function(mod) {
if (!mod.resource) {
// if (mod.reasons[0]) {
// mod.resource = mod.reasons[0].dependency.request;
// } else {
mod.resource = mod.request || mod.name || mod.reasons[0].dependency.request;
// }
// try {
// mod.resource = require.resolve(mod.reasons[0].dependency.request);
// } catch (e) {
// try {
// mod.resource = require.resolve(mod.reasons[0].module.context + '/' + mod.reasons[0].dependency.request);
// } catch (e) {
// mod.resource = mod.reasons[0].module.context + '/' + mod.reasons[0].dependency.request;
// }
// }
// console.log(mod.resource);
}
})
}
//生成script标签到console或是文件
function generateScript(chunks, outputScriptFile, BelongChunksToEntryChunk, parentsChunkNameArr) {
var entrychunk, chunk,
scriptTpl = '<script src=\"$path$\"></script>\n';
colorScriptTpl = '<script src=\"\033[32m$path$\033[0m\"></script>'
outputFileName = compilation.options.output.filename, // [name].js
outputPath = getRelativeResourcePath(compilation.options.output.publicPath ? compilation.options.output.publicPath : compilation.options.output.path + FILESLASH), // './build/dest' + '/'
genScriptStringObj = genScriptString(),
scriptString = genScriptStringObj.finalString,
scriptJson = genScriptStringObj.finalJson;
if (outputScriptFile) {
//输出到文件中
(function() {
var fileStr = '/**\n' + scriptString + '*/\nmodule.exports = ';
fileStr += JSON.stringify(scriptJson, null, 4);
fs.writeFileSync(path.resolve(getProjectPath() + outputScriptFile), fileStr);
})()
}
function genScriptString() {
var finalString = '',
entryToChunk = {},
finalJson = {};
//转换一下
for (chunk in BelongChunksToEntryChunk) {
entrychunks = BelongChunksToEntryChunk[chunk];
entrychunks.forEach(function(entrychunk) {
if (!entryToChunk[entrychunk]) {
entryToChunk[entrychunk] = [];
}
if (!in_array(chunk, entryToChunk[entrychunk])) {
entryToChunk[entrychunk].push(chunk);
}
})
}
//找到当中的parent放在最开头,entry放在最后
for (entry in entryToChunk) {
parentsChunkNameArr.forEach(function(parentchunk) {
var parentIndex = in_array(parentchunk, entryToChunk[entry]),
entryIndex,
commonIndex,
temp;
if (parentIndex) {
temp = entryToChunk[entry].splice(parentIndex, 1);
entryToChunk[entry].unshift(temp[0]);
}
entryIndex = in_array(entry, entryToChunk[entry]);
if (entryIndex) {
temp = entryToChunk[entry].splice(entryIndex, 1);
entryToChunk[entry].push(temp[0]);
}
})
}
for (entrychunk in entryToChunk) {
if (!outputScriptFile) {
console.log('\033[32m' + entrychunk + ' : \033[0m');
}
finalString = finalString + entrychunk + '\n';
finalJson[entrychunk] = [];
entryToChunk[entrychunk].forEach(function(chunkname) {
var nameStr = outputPath + outputFileName.replace(/\[name\]/g, chunkname),
colorScriptStr = colorScriptTpl.replace(/\$path\$/g, nameStr);
scriptStr = scriptTpl.replace(/\$path\$/g, nameStr);
if (!outputScriptFile) {
console.log(colorScriptStr);
}
finalString += scriptStr;
finalJson[entrychunk].push(nameStr);
})
}
return {
finalString: finalString,
finalJson: finalJson
}
}
}
//移除所有没有module的空chunk
function removeAllEmptyChunk(chunks) {
var i;
for (i = chunks.length - 1; i > -1; i--) {
if (chunks[i].modules.length == 0) {
chunks.splice(i, 1);
}
}
}
//返回应该有webpack初始化函数的chunkName
function findParents(config, entryChunks, commonChunk) {
var commonModules = commonChunk.modules,
commonModObj = getRelativeModResToMod(commonModules),
allModObj = getRelativeModResToMod(allModules),
chunkAmountObj = {},
entriesResources = {},
moduleResToEntryResObj = {},
entryChunkToBelongChunks = {},
moduleResToChunk = {},
BelongChunksToEntryChunk = {},
entryResToEntryChunk = {},
entryChunkToEntryRes = {},
UsedTimeObj = {},
siblingChunkObj = {},
targetChunks = [],
parentsChunkArr = [],
chunkName, moduleName,
entriesNames = [],
parentsChunkObj = {},
longest = 0,
longestChunk,
longestChunkName,
ramdomChunkExceptEntry,
configChunkName,
entryRes,
moduleRes,
entryChunkName,
targetChunk;
/* moduleResToChunk = {
* 'module resource' : 'chunk',
* 'module resource' : 'chunk',
* ...
* }
* moduleResToChunk = {
* 'module resource' : ['chunk1', 'chunk2'],
* 'module resource' : ['chunk'],
* ...
* }
*/
for (chunkName in config) {
config[chunkName].forEach(function(moduleName) {
if (!moduleResToChunk[addProjectPath(moduleName)]) {
moduleResToChunk[addProjectPath(moduleName)] = [];
}
if (!in_array(chunkName, moduleResToChunk[addProjectPath(moduleName)])) {
moduleResToChunk[addProjectPath(moduleName)].push(chunkName);
}
})
}
/* entriesResources = {
* '入口.resource' : ['module.resource', 'module.resource' ...],
* '入口.resource' : ['module.resource', 'module.resource' ...]
* }
*/
entriesResources = getEntryDependencies(compilation);
/*
* moduleResToEntryResObj = {
* 'config的module.resource':['该module所在的入口.resource', '第二个入口的resource'],
* 'config的module.resource':['该module所在的入口.resource'],
* ...
* }
*/
for (entryRes in entriesResources) {
entriesResources[entryRes].forEach(function(moduleRes){
if (!moduleResToEntryResObj[moduleRes]) {
moduleResToEntryResObj[moduleRes] = [];
}
if (!in_array(entryRes, moduleResToEntryResObj[moduleRes])) {
moduleResToEntryResObj[moduleRes].push(entryRes);
}
})
}
/*
* entriesNames: ['入口module所在的configChunkName', '入口module所在的configChunkName'];
* entryResToEntryChunk: {
* 'entry module resource': 'entry chunk',
* 'entry module resource': 'entry chunk',
* ...
* }
* entryChunkToEntryRes: {
* 'entry chunk': 'entry module resource',
* 'entry chunk': 'entry module resource',
* ...
* }
*/
for (chunkname in config) {
config[chunkname].forEach(function(moduleRes) {
var fullModuleRes = addProjectPath(moduleRes);
if (fullModuleRes in entriesResources) {
if (!in_array(chunkname, entriesNames)) {
entriesNames.push(chunkname);
}
entryResToEntryChunk[fullModuleRes] = chunkname;
entryChunkToEntryRes[chunkname] = fullModuleRes;
}
})
}
/*
*比较关键的是这个函数。每一个入口函数,所依赖的chunk。
* entryChunkToBelongChunks = {
* 'config entry chunk' : [chunk, chunk, ...],
* 'config entry chunk' : [chunk, chunk, ...],
* ...
* }
*/
for (entryRes in entriesResources) {
entryChunkToBelongChunks[ moduleResToChunk[entryRes][0] ] = [];
entriesResources[ entryRes ].forEach(function(moduleRes) {
moduleResToChunk[moduleRes].forEach(function(chunkname) {
/**
* 这里对于每一个入口chunk,依赖的modules,每一个module所在chunk都添加进来.
* 但是这样就所有带有这个module的chunk都添加了进来,其实是冗余的
*/
entryChunkToBelongChunks[ moduleResToChunk[entryRes][0] ].push(chunkname);
})
})
entryChunkToBelongChunks[ moduleResToChunk[entryRes][0] ] = removeDuplicates(entryChunkToBelongChunks[moduleResToChunk[entryRes][0]]);
}
/**
* 这时候的entryChunkToBelongChunks充满了冗余的chunk,必须要去除。
* 使用贪心算法,去除不需要文件,找到最优解。
* 当前这个入口所需要的所有modules, 拥有这些module的所有chunks,现在要去除重复没必要的chunk,寻求精简的最优解
*/
function filterChunk(needModules, chunks) {
var noNeedChunk = [];
var finalChunks;
//找到每一个chunks里面相对不需要的,最大的那个,去除。
function findBiggest(chunks) {
var chunkSizeObj = {},
biggestSize = 0,
biggestChunk,
chunkname;
chunks.forEach(function(chunkname) {
var size = config[chunkname].reduce(function(a, b) {
return a + allModObj[b].size();
}, 0);
chunkSizeObj[chunkname] = size;
})
for (chunkname in chunkSizeObj) {
if (chunkSizeObj[chunkname] > biggestSize) {
biggestSize = chunkSizeObj[chunkname];
biggestChunk = chunkname;
}
}
return biggestChunk
};
//是否需要这个chunk
function isNeed(targetChunk, chunks, needModules) {
var tempObj = {},
need = false;
chunks = removeChunk(targetChunk, chunks);
chunks.forEach(function(chunk) {
config[chunk].forEach(function(module) {
tempObj[module] = true;
})
})
needModules.forEach(function(module) {
if (!tempObj[getRelativeResource(module)]) {
need = true;
}
})
return need
};
//移除这个chunk
function removeChunk(targetChunk ,chunks) {
var tempChunks = JSON.parse(JSON.stringify(chunks));
tempChunks.forEach(function(chunkname, index) {
if (chunkname == targetChunk) {
tempChunks.splice(index, 1);
}
});
return tempChunks
};
// main
// 找不需要的chunk,然后纪录下来。
chunks.forEach(function(chunk) {
if (!isNeed(chunk, chunks, needModules)) {
noNeedChunk.push(chunk);
}
})
//找不到不需要chunk了,就直接返回原本的chunk
if (noNeedChunk.length == 0) {
return chunks
}
// 找到了一些不需要的chunk,就找他们体积最大的去除。
chunk = findBiggest(noNeedChunk);
finalChunks = removeChunk(chunk, chunks);
//递归再继续
return filterChunk(needModules, finalChunks);
}
//开始执行贪心算法
for (chunkname in entryChunkToBelongChunks) {
entryChunkToBelongChunks[chunkname] = filterChunk(entriesResources[entryChunkToEntryRes[chunkname]], entryChunkToBelongChunks[chunkname]);
}
/*
* BelongChunksToEntryChunk = {
* 'chunk' : ['entry chunk', 'entry chunk'],
* 'chunk' : ['entry chunk'],
* ...
* }
*/
for (entryChunkName in entryChunkToBelongChunks) {
entryChunkToBelongChunks[entryChunkName].forEach(function(chunkname) {
if (!BelongChunksToEntryChunk[chunkname]) {
BelongChunksToEntryChunk[chunkname] = [];
}
if (!in_array(entryChunkName, BelongChunksToEntryChunk[chunkname])) {
BelongChunksToEntryChunk[chunkname].push(entryChunkName);
}
})
}
/**
* 兄弟chunk:被自己的所有入口chunk引用的所有其他chunk,包括自己
* siblingChunkObj: {
* '每一个chunkname': ['chunkname', 'chunkname'],
* '每一个chunkname': ['chunkname'],
* '每一个chunkname': ['chunkname', 'chunkname'],
* }
*/
for (chunkname in config) {
BelongChunksToEntryChunk[chunkname].forEach(function(entryChunk) {
entryChunkToBelongChunks[entryChunk].forEach(function(siblingChunk) {
if (!siblingChunkObj[chunkname]) {
siblingChunkObj[chunkname] = [siblingChunk];
} else {
if (!in_array(siblingChunk, siblingChunkObj[chunkname])) {
siblingChunkObj[chunkname].push(siblingChunk);
}
}
})
})
}
/**
* UsedTimeObj,每一个chunk被页面需要的次数
*/
for (chunkname in BelongChunksToEntryChunk) {
if ((BelongChunksToEntryChunk[chunkname].length == 1) && (BelongChunksToEntryChunk[chunkname][0] == chunkname)) {
UsedTimeObj[chunkname] = 0;
} else {
UsedTimeObj[chunkname] = BelongChunksToEntryChunk[chunkname].length;
}
}
/**
* 执行寻找parent的算法
*/
// console.log(entryChunkToBelongChunks);
// console.log(BelongChunksToEntryChunk);
// console.log(siblingChunkObj);
// console.log(UsedTimeObj);
var notEntry = '$$notEntry$$',
noParents = '$$noParents$$';
for (chunkname in config) {
var mostUsedChunk = findMostUsedChunk(siblingChunkObj[chunkname], chunkname, UsedTimeObj, parentsChunkObj, parentsChunkArr, notEntry, noParents, compilation);
//如果发现没有能找到entry说明进入了死锁情景。那么就拿一个已有的parentChunk作为入口
if (mostUsedChunk == chunkname && siblingChunkObj[chunkname].length > 1) {
parentsChunkObj[chunkname] = noParents;
}
siblingChunkObj[chunkname].forEach(function(sibling) {
if (sibling == mostUsedChunk) {
parentsChunkObj[chunkname] = mostUsedChunk;
pushWithoutDuplication(mostUsedChunk, parentsChunkArr);
} else if (!(sibling in entryChunkToBelongChunks) && !parentsChunkObj[chunkname]) {
parentsChunkObj[chunkname] = notEntry;
}
})
}
// console.log(parentsChunkObj);
// console.log(parentsChunkArr);
/**
* 如果commonChunkplugin的逻辑帮我们分析出了全部公共模块
* 找出这些公共模块在config中所在的所有chunk
* 找出这些chunk中最大的一个
* 作为entry=true的chunk。
*/
// if (commonModules.length) {
// for (moduleName in commonModObj) {
// for (chunkName in config) {
// config[chunkName].forEach(function(configModule) {
// if (configModule == moduleName) {
// chunkAmountObj[chunkName] = config[chunkName].length;
// }
// })
// }
// }
// for (chunkName in chunkAmountObj) {
// if (chunkAmountObj[chunkName] > longest) {
// longest = chunkAmountObj[chunkName];
// longestChunkName = chunkName;
// }
// }
// entriesNames.push(longestChunkName);
// for (chunkName in config) {
// parentsChunkObj[chunkName] = longestChunkName;
// }
// parentsChunkObj[longestChunkName] ='';
// parentsChunkArr.push(longestChunkName);
// }
// /*
// * 如果commonChunkplugin的逻辑发现,所以入口之间不存在公共模块
// * 找所有该入口依赖的chunks
// * 随便找一个chunk,只要它不是入口chunk。
// * 作为parent chunk
// */
// if (commonModules.length == 0) {
// // if (true) {
// //parentsChunkObj
// for (chunkname in config) {
// (function(chunkname){
// BelongChunksToEntryChunk[chunkname].forEach(function(tempEntryChunk) {
// entryChunkToBelongChunks[tempEntryChunk].forEach(function(chunk) {
// if (chunk == tempEntryChunk && chunk!= chunkname) {
// return
// } else {
// targetChunk = chunk;
// }
// })
// entryChunkToBelongChunks[tempEntryChunk].forEach(function(chunk) {
// parentsChunkObj[chunk] = targetChunk;
// })
// })
// })(chunkname);
// }
// for (chunkname in parentsChunkObj) {
// if (parentsChunkObj[chunkname] == chunkname) {
// parentsChunkObj[chunkname] = '';
// parentsChunkArr.push(chunkname);
// }
// }
// }
/*
* parentsChunkObj = {
* 'config chunkname' : '成为parent的config chunkname(不能是入口chunk,不能是其它入口依赖的chunk)',
* 'config chunkname' : '成为parent的config chunkname(不能是入口chunk,不能是其它入口依赖的chunk)',
* '成为parent的config chunkname' : '',
* '成为parent的config chunkname' : '',
* ...
* }
*/
return {
'entriesNamesArr': entriesNames,
'parentsChunkNameObj': parentsChunkObj,
'parentsChunkNameArr': parentsChunkArr,
'BelongChunksToEntryChunk': BelongChunksToEntryChunk
}
}
/*
* 生成单个chunk
* @param newModuleName {string} 新建模块名称
* @param targetModules {array} module 需要放到chunk里面的module数组
* @param parentChunk {chunk} 指定的父chunk。
*/
function generateChunk(newChunkName, targetModules, isEntry, chunks, parentsChunk) {
var newChunk,
alreadyHasThisChunk = false,
alreadyInThisChunk = false,
_this = this;
chunks.forEach(function(chunk) {
if (chunk.name == newChunkName) {
alreadyHasThisChunk = true;
newChunk = chunk;
}
})
targetModules.forEach(function(targetModule) {
if (!alreadyHasThisChunk) {
newChunk = _this.addChunk(newChunkName);
}
//entry为false
newChunk.initial = true;
newChunk.entry = isEntry;
newChunk.parents = [];
parentsChunk.forEach(function(parentchunk) {
newChunk.addParent(parentchunk);
})
// targetModule.chunks.forEach(function(chunk) {
// originChunks.forEach(function(originChunk) {
// if (originChunk == chunk) {
// targetModule.removeChunk(chunk); // 从旧的chunk中移除
// };
// })
// })
//目标module是不是已经在newchunk里面了是的话就不重复添加
newChunk.modules.forEach(function(module) {
if (module.resource == targetModule.resource) {
alreadyInThisChunk = true;
}
})
if (!alreadyInThisChunk) {
newChunk.addModule(targetModule);
}
targetModule.addChunk(newChunk); // 添加到新的chunk中去
newChunk.chunks = [];
})
return newChunk
}
//获取依赖关系
function getEntryDependencies(compilation) {
var entriesResources = {};
function getDependecies(depBlock, parentDependecies) {
var dependencies = [];
if (in_array(depBlock.resource, parentDependecies)) {
// console.log('--存在循环依赖:---');
// console.log(depBlock.resource);
// console.log('-----------------');
// console.log('former res : ' + depBlock.resource);
// console.log('parent : ' + depObj[depBlock.resource].parent);
// console.log('-----------');
pushWithoutDuplication(getModuleResource(depBlock), dependencies);
return dependencies
}
pushWithoutDuplication(getModuleResource(depBlock), dependencies);
depBlock.dependencies.forEach(function(dep) {
if (dep.module) {
dependencies = dependencies.concat(getDependecies(dep.module, parentDependecies.concat([depBlock.resource])));
}
})
return dependencies
}
compilation.entries.forEach(function(entry) {
var entryRes = getModuleResource(entry);
entriesResources[entryRes] = [];
entry.dependencies.forEach(function(dep) {
if (dep.module) {
entriesResources[entryRes] = entriesResources[entryRes].concat(getDependecies(dep.module, getModuleResource(dep.module) == entryRes ? [] : [entryRes]));
}
})
entriesResources[entryRes].push(entryRes);
entriesResources[entryRes] = removeDuplicates(entriesResources[entryRes]);
})
return entriesResources
}
//获取依赖关系中所有module resource(用来和config中的做对比,看看是否有差异)
function getAllDependenciesRes(compilation) {
var allDependencies = [],
entriesResources = getEntryDependencies(compilation),
entry;
for (entry in entriesResources) {
entriesResources[entry].forEach(function(modRes) {
allDependencies.push(modRes);
})
}
return removeDuplicates(allDependencies);
}
function parseConfigIntolinuxStyle(config) {
var newConfig;
if (PLATFORM == 'WIN') {
newConfig = JSON.parse(JSON.stringify(config).replace(/\\+/g, '/'));
}
return newConfig
}
function parseConfigIntoLocalStyle(config) {
var newConfig = {};
if (PLATFORM == 'WIN') {
for (var i in config) {
if (!newConfig[i.replace(/\/+/g, '\\\\')]) {
newConfig[i.replace(/\/+/g, '\\\\')] = [];
};
config[i].forEach(function(item) {
newConfig[i.replace(/\/+/g, '\\\\')].push(item.replace(/\/+/g, '\\'));
})
}
}
return newConfig
}
/**
* generateConfig 不拆分,所有chunk保持原样
*/
function generateConfig(chunks, commonChunks, entries, bundleFiles) {
var config = {},
pathModObj,
key,
chunkname,
noCommon = false;
removeAllEmptyChunk(chunks);
chunks.forEach(function(chunk) {
var modName;
// 非异步模块
if (chunk.initial == true) {
pathModObj = getModuleRelativePathObjWithoutType(chunk.modules);
config[chunk.name] = [];
for (modName in pathModObj) {
config[chunk.name].push(getRelativeResource(getModuleResource(pathModObj[modName])));
}
config[chunk.name] = removeDuplicates(config[chunk.name]);
}
})
// bundleFiles参数
for (chunkname in config) {
bundleFiles.forEach(function(file) {
if (isChunkInFile(file, chunkname)) {
if (!Array.isArray(config[file])) {
config[file] = [];
}
config[file] = config[file].concat(config[chunkname]);
delete config[chunkname];
}
})
}
return config
}
function isChunkInFile(file, chunkName) {
var isTrue = false,
tempFile;
if (chunkName.length > file.length) {
tempFile = chunkName.substring(0, file.length);
if (tempFile == file) {
isTrue = true;
}
}
return isTrue
}
function getConfig() {
var configLoc = getConfigPath(),
config, ret, bool;
try {
config = require(configLoc);
} catch (e) {
config = false
}
return config
}
//验证config的格式 返回真假
function testConfig(config) {
//config里面包含的所有文件
var configResArr = [],
missingFiles = [],
ret = {}; // 错误返回值。
//判断的主要逻辑 (先判断是否符合格式)
if (configStruct()) {
for (chunkname in config) {
config[chunkname].forEach(function(modName) {
configResArr.push(addProjectPath(modName));
})
}
if (
emptyChunk() && // 空的chunk 不允许
checkChunkDuplication() && // chunk内不允许重复,总体允许
// checkDuplication() && // 重复文件 (@todo应该允许,但是感觉很不好做)
checkMissingEntryFile() && // 不允许丢失入口文件
extraFile() //多余文件,不允许。
) {
//满足上述情况下,如果有丢失的文件,那么找出来。
checkMissingFile(config);
return true
} else {
return false
}
} else {
return false
}
//config格式一定要是obj,每一个value都是数组,并且里面的值都是字符串
function configStruct() {
var ret = true, chunkname;
if (typeof config !== 'object' || Array.isArray(config)) {
compilation.errors.push(new Error("seperate.config.js输出格式一定要是object"));
ret = false;
} else {
for (chunkname in config) {
if (!Array.isArray(config[chunkname])) {
compilation.errors.push(new Error("seperate.config.js输出每一个value一定都是数组"));
ret = false;
}
}
if (ret) {
for (chunkname in config) {
config[chunkname].forEach(function(modRes) {
if (typeof modRes != 'string') {
compilation.errors.push(new Error("seperate.config.js输出,数组里面都需要是string类型"));
ret = false;
}
})
}
}
}
return ret
}
//config中的配置文件没有重复
function checkDuplication() {
var hash = {}, wrongFile = [], ret = true;
for (var i = 0, elem; (elem = configResArr[i]) != null; i++) {
if (!hash[elem]) {
hash[elem] = true;