RemoveEmptyChunksPlugin.js 1.4 KB

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