ChunkModuleIdRangePlugin.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { find } = require("../util/SetHelpers");
  7. const {
  8. compareModulesByPreOrderIndexOrIdentifier,
  9. compareModulesByPostOrderIndexOrIdentifier
  10. } = require("../util/comparators");
  11. /** @typedef {import("../Compiler")} Compiler */
  12. /**
  13. * @typedef {object} ChunkModuleIdRangePluginOptions
  14. * @property {string} name the chunk name
  15. * @property {("index" | "index2" | "preOrderIndex" | "postOrderIndex")=} order order
  16. * @property {number=} start start id
  17. * @property {number=} end end id
  18. */
  19. class ChunkModuleIdRangePlugin {
  20. /**
  21. * @param {ChunkModuleIdRangePluginOptions} options options object
  22. */
  23. constructor(options) {
  24. this.options = options;
  25. }
  26. /**
  27. * Apply the plugin
  28. * @param {Compiler} compiler the compiler instance
  29. * @returns {void}
  30. */
  31. apply(compiler) {
  32. const options = this.options;
  33. compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => {
  34. const moduleGraph = compilation.moduleGraph;
  35. compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => {
  36. const chunkGraph = compilation.chunkGraph;
  37. const chunk = find(
  38. compilation.chunks,
  39. chunk => chunk.name === options.name
  40. );
  41. if (!chunk) {
  42. throw new Error(
  43. `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found`
  44. );
  45. }
  46. let chunkModules;
  47. if (options.order) {
  48. let cmpFn;
  49. switch (options.order) {
  50. case "index":
  51. case "preOrderIndex":
  52. cmpFn = compareModulesByPreOrderIndexOrIdentifier(moduleGraph);
  53. break;
  54. case "index2":
  55. case "postOrderIndex":
  56. cmpFn = compareModulesByPostOrderIndexOrIdentifier(moduleGraph);
  57. break;
  58. default:
  59. throw new Error(
  60. "ChunkModuleIdRangePlugin: unexpected value of order"
  61. );
  62. }
  63. chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn);
  64. } else {
  65. chunkModules = Array.from(modules)
  66. .filter(m => chunkGraph.isModuleInChunk(m, chunk))
  67. .sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph));
  68. }
  69. let currentId = options.start || 0;
  70. for (let i = 0; i < chunkModules.length; i++) {
  71. const m = chunkModules[i];
  72. if (m.needId && chunkGraph.getModuleId(m) === null) {
  73. chunkGraph.setModuleId(m, currentId++);
  74. }
  75. if (options.end && currentId > options.end) break;
  76. }
  77. });
  78. });
  79. }
  80. }
  81. module.exports = ChunkModuleIdRangePlugin;