RemoveEmptyChunksPlugin.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. const PLUGIN_NAME = "RemoveEmptyChunksPlugin";
  10. class RemoveEmptyChunksPlugin {
  11. /**
  12. * Apply the plugin
  13. * @param {Compiler} compiler the compiler instance
  14. * @returns {void}
  15. */
  16. apply(compiler) {
  17. compiler.hooks.compilation.tap(PLUGIN_NAME, compilation => {
  18. /**
  19. * @param {Iterable<Chunk>} chunks the chunks array
  20. * @returns {void}
  21. */
  22. const handler = chunks => {
  23. const chunkGraph = compilation.chunkGraph;
  24. for (const chunk of chunks) {
  25. if (
  26. chunkGraph.getNumberOfChunkModules(chunk) === 0 &&
  27. !chunk.hasRuntime() &&
  28. chunkGraph.getNumberOfEntryModules(chunk) === 0
  29. ) {
  30. compilation.chunkGraph.disconnectChunk(chunk);
  31. compilation.chunks.delete(chunk);
  32. }
  33. }
  34. };
  35. // TODO do it once
  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;