ChunkModuleIdRangePlugin.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const sortByIndex = (a, b) => {
  7. return a.index - b.index;
  8. };
  9. const sortByIndex2 = (a, b) => {
  10. return a.index2 - b.index2;
  11. };
  12. class ChunkModuleIdRangePlugin {
  13. constructor(options) {
  14. this.options = options;
  15. }
  16. apply(compiler) {
  17. const options = this.options;
  18. compiler.hooks.compilation.tap("ChunkModuleIdRangePlugin", compilation => {
  19. compilation.hooks.moduleIds.tap("ChunkModuleIdRangePlugin", modules => {
  20. const chunk = compilation.chunks.find(
  21. chunk => chunk.name === options.name
  22. );
  23. if (!chunk) {
  24. throw new Error(
  25. `ChunkModuleIdRangePlugin: Chunk with name '${options.name}"' was not found`
  26. );
  27. }
  28. let chunkModules;
  29. if (options.order) {
  30. chunkModules = Array.from(chunk.modulesIterable);
  31. switch (options.order) {
  32. case "index":
  33. chunkModules.sort(sortByIndex);
  34. break;
  35. case "index2":
  36. chunkModules.sort(sortByIndex2);
  37. break;
  38. default:
  39. throw new Error(
  40. "ChunkModuleIdRangePlugin: unexpected value of order"
  41. );
  42. }
  43. } else {
  44. chunkModules = modules.filter(m => {
  45. return m.chunksIterable.has(chunk);
  46. });
  47. }
  48. let currentId = options.start || 0;
  49. for (let i = 0; i < chunkModules.length; i++) {
  50. const m = chunkModules[i];
  51. if (m.id === null) {
  52. m.id = currentId++;
  53. }
  54. if (options.end && currentId > options.end) break;
  55. }
  56. });
  57. });
  58. }
  59. }
  60. module.exports = ChunkModuleIdRangePlugin;