ModuleChunkLoadingPlugin.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RuntimeGlobals = require("../RuntimeGlobals");
  7. const ExportWebpackRequireRuntimeModule = require("./ExportWebpackRequireRuntimeModule");
  8. const ModuleChunkLoadingRuntimeModule = require("./ModuleChunkLoadingRuntimeModule");
  9. /** @typedef {import("../Compiler")} Compiler */
  10. class ModuleChunkLoadingPlugin {
  11. /**
  12. * Apply the plugin
  13. * @param {Compiler} compiler the compiler instance
  14. * @returns {void}
  15. */
  16. apply(compiler) {
  17. compiler.hooks.thisCompilation.tap(
  18. "ModuleChunkLoadingPlugin",
  19. compilation => {
  20. const globalChunkLoading = compilation.outputOptions.chunkLoading;
  21. const isEnabledForChunk = chunk => {
  22. const options = chunk.getEntryOptions();
  23. const chunkLoading =
  24. options && options.chunkLoading !== undefined
  25. ? options.chunkLoading
  26. : globalChunkLoading;
  27. return chunkLoading === "import";
  28. };
  29. const onceForChunkSet = new WeakSet();
  30. const handler = (chunk, set) => {
  31. if (onceForChunkSet.has(chunk)) return;
  32. onceForChunkSet.add(chunk);
  33. if (!isEnabledForChunk(chunk)) return;
  34. set.add(RuntimeGlobals.moduleFactoriesAddOnly);
  35. set.add(RuntimeGlobals.hasOwnProperty);
  36. compilation.addRuntimeModule(
  37. chunk,
  38. new ModuleChunkLoadingRuntimeModule(set)
  39. );
  40. };
  41. compilation.hooks.runtimeRequirementInTree
  42. .for(RuntimeGlobals.ensureChunkHandlers)
  43. .tap("ModuleChunkLoadingPlugin", handler);
  44. compilation.hooks.runtimeRequirementInTree
  45. .for(RuntimeGlobals.baseURI)
  46. .tap("ModuleChunkLoadingPlugin", handler);
  47. compilation.hooks.runtimeRequirementInTree
  48. .for(RuntimeGlobals.externalInstallChunk)
  49. .tap("ModuleChunkLoadingPlugin", handler);
  50. compilation.hooks.runtimeRequirementInTree
  51. .for(RuntimeGlobals.onChunksLoaded)
  52. .tap("ModuleChunkLoadingPlugin", handler);
  53. compilation.hooks.runtimeRequirementInTree
  54. .for(RuntimeGlobals.externalInstallChunk)
  55. .tap("ModuleChunkLoadingPlugin", (chunk, set) => {
  56. if (!isEnabledForChunk(chunk)) return;
  57. compilation.addRuntimeModule(
  58. chunk,
  59. new ExportWebpackRequireRuntimeModule()
  60. );
  61. });
  62. compilation.hooks.runtimeRequirementInTree
  63. .for(RuntimeGlobals.ensureChunkHandlers)
  64. .tap("ModuleChunkLoadingPlugin", (chunk, set) => {
  65. if (!isEnabledForChunk(chunk)) return;
  66. set.add(RuntimeGlobals.getChunkScriptFilename);
  67. });
  68. }
  69. );
  70. }
  71. }
  72. module.exports = ModuleChunkLoadingPlugin;