You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.0 KiB

4 years ago
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const GraphHelpers = require("../GraphHelpers");
  7. class EnsureChunkConditionsPlugin {
  8. apply(compiler) {
  9. compiler.hooks.compilation.tap(
  10. "EnsureChunkConditionsPlugin",
  11. compilation => {
  12. const handler = chunks => {
  13. let changed = false;
  14. for (const module of compilation.modules) {
  15. if (!module.chunkCondition) continue;
  16. const sourceChunks = new Set();
  17. const chunkGroups = new Set();
  18. for (const chunk of module.chunksIterable) {
  19. if (!module.chunkCondition(chunk)) {
  20. sourceChunks.add(chunk);
  21. for (const group of chunk.groupsIterable) {
  22. chunkGroups.add(group);
  23. }
  24. }
  25. }
  26. if (sourceChunks.size === 0) continue;
  27. const targetChunks = new Set();
  28. chunkGroupLoop: for (const chunkGroup of chunkGroups) {
  29. // Can module be placed in a chunk of this group?
  30. for (const chunk of chunkGroup.chunks) {
  31. if (module.chunkCondition(chunk)) {
  32. targetChunks.add(chunk);
  33. continue chunkGroupLoop;
  34. }
  35. }
  36. // We reached the entrypoint: fail
  37. if (chunkGroup.isInitial()) {
  38. throw new Error(
  39. "Cannot fullfil chunk condition of " + module.identifier()
  40. );
  41. }
  42. // Try placing in all parents
  43. for (const group of chunkGroup.parentsIterable) {
  44. chunkGroups.add(group);
  45. }
  46. }
  47. for (const sourceChunk of sourceChunks) {
  48. GraphHelpers.disconnectChunkAndModule(sourceChunk, module);
  49. }
  50. for (const targetChunk of targetChunks) {
  51. GraphHelpers.connectChunkAndModule(targetChunk, module);
  52. }
  53. }
  54. if (changed) return true;
  55. };
  56. compilation.hooks.optimizeChunksBasic.tap(
  57. "EnsureChunkConditionsPlugin",
  58. handler
  59. );
  60. compilation.hooks.optimizeExtractedChunksBasic.tap(
  61. "EnsureChunkConditionsPlugin",
  62. handler
  63. );
  64. }
  65. );
  66. }
  67. }
  68. module.exports = EnsureChunkConditionsPlugin;