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. const PLUGIN_NAME = "ChunkModuleIdRangePlugin";
  20. class ChunkModuleIdRangePlugin {
  21. /**
  22. * @param {ChunkModuleIdRangePluginOptions} options options object
  23. */
  24. constructor(options) {
  25. this.options = options;
  26. }
  27. /**
  28. * Apply the plugin
  29. * @param {Compiler} compiler the compiler instance
  30. * @returns {void}
  31. */
  32. apply(compiler) {
  33. const options = this.options;
  34. compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
  35. const moduleGraph = compilation.moduleGraph;
  36. compilation.hooks.moduleIds.tap(PLUGIN_NAME, modules => {
  37. const chunkGraph = compilation.chunkGraph;
  38. const chunk = find(
  39. compilation.chunks,
  40. chunk => chunk.name === options.name
  41. );
  42. if (!chunk) {
  43. throw new Error(
  44. `${PLUGIN_NAME}: Chunk with name '${options.name}"' was not found`
  45. );
  46. }
  47. let chunkModules;
  48. if (options.order) {
  49. let cmpFn;
  50. switch (options.order) {
  51. case "index":
  52. case "preOrderIndex":
  53. cmpFn = compareModulesByPreOrderIndexOrIdentifier(moduleGraph);
  54. break;
  55. case "index2":
  56. case "postOrderIndex":
  57. cmpFn = compareModulesByPostOrderIndexOrIdentifier(moduleGraph);
  58. break;
  59. default:
  60. throw new Error(`${PLUGIN_NAME}: unexpected value of order`);
  61. }
  62. chunkModules = chunkGraph.getOrderedChunkModules(chunk, cmpFn);
  63. } else {
  64. chunkModules = Array.from(modules)
  65. .filter(m => chunkGraph.isModuleInChunk(m, chunk))
  66. .sort(compareModulesByPreOrderIndexOrIdentifier(moduleGraph));
  67. }
  68. let currentId = options.start || 0;
  69. for (let i = 0; i < chunkModules.length; i++) {
  70. const m = chunkModules[i];
  71. if (m.needId && chunkGraph.getModuleId(m) === null) {
  72. chunkGraph.setModuleId(m, currentId++);
  73. }
  74. if (options.end && currentId > options.end) break;
  75. }
  76. });
  77. });
  78. }
  79. }
  80. module.exports = ChunkModuleIdRangePlugin;