chunksorter.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. 'use strict';
  2. const toposort = require('toposort');
  3. const _ = require('lodash');
  4. /**
  5. Sorts dependencies between chunks by their "parents" attribute.
  6. This function sorts chunks based on their dependencies with each other.
  7. The parent relation between chunks as generated by Webpack for each chunk
  8. is used to define a directed (and hopefully acyclic) graph, which is then
  9. topologically sorted in order to retrieve the correct order in which
  10. chunks need to be embedded into HTML. A directed edge in this graph is
  11. describing a "is parent of" relationship from a chunk to another (distinct)
  12. chunk. Thus topological sorting orders chunks from bottom-layer chunks to
  13. highest level chunks that use the lower-level chunks.
  14. @param {Array} chunks an array of chunks as generated by the html-webpack-plugin.
  15. - For webpack < 4, It is assumed that each entry contains at least the properties
  16. "id" (containing the chunk id) and "parents" (array containing the ids of the
  17. parent chunks).
  18. - For webpack 4+ the see the chunkGroups param for parent-child relationships
  19. @param {Array} chunks an array of ChunkGroups that has a getParents method.
  20. Each ChunkGroup contains a list of chunks in order.
  21. @return {Array} A topologically sorted version of the input chunks
  22. */
  23. module.exports.dependency = (chunks, options, compilation) => {
  24. const chunkGroups = compilation.chunkGroups;
  25. if (!chunks) {
  26. return chunks;
  27. }
  28. // We build a map (chunk-id -> chunk) for faster access during graph building.
  29. const nodeMap = {};
  30. chunks.forEach(chunk => {
  31. nodeMap[chunk.id] = chunk;
  32. });
  33. // Next, we add an edge for each parent relationship into the graph
  34. let edges = [];
  35. if (chunkGroups) {
  36. // Add an edge for each parent (parent -> child)
  37. edges = chunkGroups.reduce((result, chunkGroup) => result.concat(
  38. Array.from(chunkGroup.parentsIterable, parentGroup => [parentGroup, chunkGroup])
  39. ), []);
  40. const sortedGroups = toposort.array(chunkGroups, edges);
  41. // flatten chunkGroup into chunks
  42. const sortedChunks = sortedGroups
  43. .reduce((result, chunkGroup) => result.concat(chunkGroup.chunks), [])
  44. .map(chunk => // use the chunk from the list passed in, since it may be a filtered list
  45. nodeMap[chunk.id])
  46. .filter((chunk, index, self) => {
  47. // make sure exists (ie excluded chunks not in nodeMap)
  48. const exists = !!chunk;
  49. // make sure we have a unique list
  50. const unique = self.indexOf(chunk) === index;
  51. return exists && unique;
  52. });
  53. return sortedChunks;
  54. } else {
  55. // before webpack 4 there was no chunkGroups
  56. chunks.forEach(chunk => {
  57. if (chunk.parents) {
  58. // Add an edge for each parent (parent -> child)
  59. chunk.parents.forEach(parentId => {
  60. // webpack2 chunk.parents are chunks instead of string id(s)
  61. const parentChunk = _.isObject(parentId) ? parentId : nodeMap[parentId];
  62. // If the parent chunk does not exist (e.g. because of an excluded chunk)
  63. // we ignore that parent
  64. if (parentChunk) {
  65. edges.push([parentChunk, chunk]);
  66. }
  67. });
  68. }
  69. });
  70. // We now perform a topological sorting on the input chunks and built edges
  71. return toposort.array(chunks, edges);
  72. }
  73. };
  74. /**
  75. * Sorts the chunks based on the chunk id.
  76. *
  77. * @param {Array} chunks the list of chunks to sort
  78. * @return {Array} The sorted list of chunks
  79. */
  80. module.exports.id = chunks => chunks.sort(function orderEntryLast (a, b) {
  81. if (a.entry !== b.entry) {
  82. return b.entry ? 1 : -1;
  83. } else {
  84. return b.id - a.id;
  85. }
  86. });
  87. /**
  88. * Performs identity mapping (no-sort).
  89. * @param {Array} chunks the chunks to sort
  90. * @return {Array} The sorted chunks
  91. */
  92. module.exports.none = chunks => chunks;
  93. /**
  94. * Sort manually by the chunks
  95. * @param {Array} chunks the chunks to sort
  96. * @return {Array} The sorted chunks
  97. */
  98. module.exports.manual = (chunks, options) => {
  99. const specifyChunks = options.chunks;
  100. const chunksResult = [];
  101. let filterResult = [];
  102. if (Array.isArray(specifyChunks)) {
  103. for (var i = 0; i < specifyChunks.length; i++) {
  104. filterResult = chunks.filter(chunk => {
  105. if (chunk.names[0] && chunk.names[0] === specifyChunks[i]) {
  106. return true;
  107. }
  108. return false;
  109. });
  110. filterResult.length > 0 && chunksResult.push(filterResult[0]);
  111. }
  112. }
  113. return chunksResult;
  114. };
  115. /**
  116. * Defines the default sorter.
  117. */
  118. module.exports.auto = module.exports.id;
  119. // In webpack 2 the ids have been flipped.
  120. // Therefore the id sort doesn't work the same way as it did for webpack 1
  121. // Luckily the dependency sort is working as expected
  122. if (Number(require('webpack/package.json').version.split('.')[0]) > 1) {
  123. module.exports.auto = module.exports.dependency;
  124. }