ChunkModuleIdRangePlugin.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 => {
  67. return chunkGraph.isModuleInChunk(m, chunk);
  68. })
  69. .sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph));
  70. }
  71. let currentId = options.start || 0;
  72. for (let i = 0; i < chunkModules.length; i++) {
  73. const m = chunkModules[i];
  74. if (m.needId && chunkGraph.getModuleId(m) === null) {
  75. chunkGraph.setModuleId(m, currentId++);
  76. }
  77. if (options.end && currentId > options.end) break;
  78. }
  79. });
  80. });
  81. }
  82. }
  83. module.exports = ChunkModuleIdRangePlugin;