ChunkModuleIdRangePlugin.js 2.1 KB

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