RemoveEmptyChunksPlugin.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { STAGE_BASIC, STAGE_ADVANCED } = require("../OptimizationStages");
  7. /** @typedef {import("../Chunk")} Chunk */
  8. /** @typedef {import("../Compiler")} Compiler */
  9. class RemoveEmptyChunksPlugin {
  10. /**
  11. * Apply the plugin
  12. * @param {Compiler} compiler the compiler instance
  13. * @returns {void}
  14. */
  15. apply(compiler) {
  16. compiler.hooks.compilation.tap("RemoveEmptyChunksPlugin", compilation => {
  17. /**
  18. * @param {Iterable<Chunk>} chunks the chunks array
  19. * @returns {void}
  20. */
  21. const handler = chunks => {
  22. const chunkGraph = compilation.chunkGraph;
  23. for (const chunk of chunks) {
  24. if (
  25. chunkGraph.getNumberOfChunkModules(chunk) === 0 &&
  26. !chunk.hasRuntime() &&
  27. chunkGraph.getNumberOfEntryModules(chunk) === 0
  28. ) {
  29. compilation.chunkGraph.disconnectChunk(chunk);
  30. compilation.chunks.delete(chunk);
  31. }
  32. }
  33. };
  34. // TODO do it once
  35. compilation.hooks.optimizeChunks.tap(
  36. {
  37. name: "RemoveEmptyChunksPlugin",
  38. stage: STAGE_BASIC
  39. },
  40. handler
  41. );
  42. compilation.hooks.optimizeChunks.tap(
  43. {
  44. name: "RemoveEmptyChunksPlugin",
  45. stage: STAGE_ADVANCED
  46. },
  47. handler
  48. );
  49. });
  50. }
  51. }
  52. module.exports = RemoveEmptyChunksPlugin;