10
0

HoistContainerReferencesPlugin.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Zackary Jackson @ScriptedAlchemy
  4. */
  5. "use strict";
  6. const AsyncDependenciesBlock = require("../AsyncDependenciesBlock");
  7. const ExternalModule = require("../ExternalModule");
  8. const { STAGE_ADVANCED } = require("../OptimizationStages");
  9. const memoize = require("../util/memoize");
  10. const { forEachRuntime } = require("../util/runtime");
  11. /** @typedef {import("../Compilation")} Compilation */
  12. /** @typedef {import("../Compiler")} Compiler */
  13. /** @typedef {import("../Dependency")} Dependency */
  14. /** @typedef {import("../Module")} Module */
  15. const getModuleFederationPlugin = memoize(() =>
  16. require("./ModuleFederationPlugin")
  17. );
  18. const PLUGIN_NAME = "HoistContainerReferences";
  19. /**
  20. * This class is used to hoist container references in the code.
  21. */
  22. class HoistContainerReferences {
  23. /**
  24. * Apply the plugin to the compiler.
  25. * @param {Compiler} compiler The webpack compiler instance.
  26. */
  27. apply(compiler) {
  28. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, compilation => {
  29. const hooks =
  30. getModuleFederationPlugin().getCompilationHooks(compilation);
  31. const depsToTrace = new Set();
  32. const entryExternalsToHoist = new Set();
  33. hooks.addContainerEntryDependency.tap(PLUGIN_NAME, dep => {
  34. depsToTrace.add(dep);
  35. });
  36. hooks.addFederationRuntimeDependency.tap(PLUGIN_NAME, dep => {
  37. depsToTrace.add(dep);
  38. });
  39. compilation.hooks.addEntry.tap(PLUGIN_NAME, entryDep => {
  40. if (entryDep.type === "entry") {
  41. entryExternalsToHoist.add(entryDep);
  42. }
  43. });
  44. // Hook into the optimizeChunks phase
  45. compilation.hooks.optimizeChunks.tap(
  46. {
  47. name: PLUGIN_NAME,
  48. // advanced stage is where SplitChunksPlugin runs.
  49. stage: STAGE_ADVANCED + 1
  50. },
  51. chunks => {
  52. this.hoistModulesInChunks(
  53. compilation,
  54. depsToTrace,
  55. entryExternalsToHoist
  56. );
  57. }
  58. );
  59. });
  60. }
  61. /**
  62. * Hoist modules in chunks.
  63. * @param {Compilation} compilation The webpack compilation instance.
  64. * @param {Set<Dependency>} depsToTrace Set of container entry dependencies.
  65. * @param {Set<Dependency>} entryExternalsToHoist Set of container entry dependencies to hoist.
  66. */
  67. hoistModulesInChunks(compilation, depsToTrace, entryExternalsToHoist) {
  68. const { chunkGraph, moduleGraph } = compilation;
  69. // loop over entry points
  70. for (const dep of entryExternalsToHoist) {
  71. const entryModule = moduleGraph.getModule(dep);
  72. if (!entryModule) continue;
  73. // get all the external module types and hoist them to the runtime chunk, this will get RemoteModule externals
  74. const allReferencedModules = getAllReferencedModules(
  75. compilation,
  76. entryModule,
  77. "external",
  78. false
  79. );
  80. const containerRuntimes = chunkGraph.getModuleRuntimes(entryModule);
  81. const runtimes = new Set();
  82. for (const runtimeSpec of containerRuntimes) {
  83. forEachRuntime(runtimeSpec, runtimeKey => {
  84. if (runtimeKey) {
  85. runtimes.add(runtimeKey);
  86. }
  87. });
  88. }
  89. for (const runtime of runtimes) {
  90. const runtimeChunk = compilation.namedChunks.get(runtime);
  91. if (!runtimeChunk) continue;
  92. for (const module of allReferencedModules) {
  93. if (!chunkGraph.isModuleInChunk(module, runtimeChunk)) {
  94. chunkGraph.connectChunkAndModule(runtimeChunk, module);
  95. }
  96. }
  97. }
  98. this.cleanUpChunks(compilation, allReferencedModules);
  99. }
  100. // handle container entry specifically
  101. for (const dep of depsToTrace) {
  102. const containerEntryModule = moduleGraph.getModule(dep);
  103. if (!containerEntryModule) continue;
  104. const allReferencedModules = getAllReferencedModules(
  105. compilation,
  106. containerEntryModule,
  107. "initial",
  108. false
  109. );
  110. const allRemoteReferences = getAllReferencedModules(
  111. compilation,
  112. containerEntryModule,
  113. "external",
  114. false
  115. );
  116. for (const remote of allRemoteReferences) {
  117. allReferencedModules.add(remote);
  118. }
  119. const containerRuntimes =
  120. chunkGraph.getModuleRuntimes(containerEntryModule);
  121. const runtimes = new Set();
  122. for (const runtimeSpec of containerRuntimes) {
  123. forEachRuntime(runtimeSpec, runtimeKey => {
  124. if (runtimeKey) {
  125. runtimes.add(runtimeKey);
  126. }
  127. });
  128. }
  129. for (const runtime of runtimes) {
  130. const runtimeChunk = compilation.namedChunks.get(runtime);
  131. if (!runtimeChunk) continue;
  132. for (const module of allReferencedModules) {
  133. if (!chunkGraph.isModuleInChunk(module, runtimeChunk)) {
  134. chunkGraph.connectChunkAndModule(runtimeChunk, module);
  135. }
  136. }
  137. }
  138. this.cleanUpChunks(compilation, allReferencedModules);
  139. }
  140. }
  141. /**
  142. * Clean up chunks by disconnecting unused modules.
  143. * @param {Compilation} compilation The webpack compilation instance.
  144. * @param {Set<Module>} modules Set of modules to clean up.
  145. */
  146. cleanUpChunks(compilation, modules) {
  147. const { chunkGraph } = compilation;
  148. for (const module of modules) {
  149. for (const chunk of chunkGraph.getModuleChunks(module)) {
  150. if (!chunk.hasRuntime()) {
  151. chunkGraph.disconnectChunkAndModule(chunk, module);
  152. if (
  153. chunkGraph.getNumberOfChunkModules(chunk) === 0 &&
  154. chunkGraph.getNumberOfEntryModules(chunk) === 0
  155. ) {
  156. chunkGraph.disconnectChunk(chunk);
  157. compilation.chunks.delete(chunk);
  158. if (chunk.name) {
  159. compilation.namedChunks.delete(chunk.name);
  160. }
  161. }
  162. }
  163. }
  164. }
  165. modules.clear();
  166. }
  167. }
  168. /**
  169. * Helper method to collect all referenced modules recursively.
  170. * @param {Compilation} compilation The webpack compilation instance.
  171. * @param {Module} module The module to start collecting from.
  172. * @param {string} type The type of modules to collect ("initial", "external", or "all").
  173. * @param {boolean} includeInitial Should include the referenced module passed
  174. * @returns {Set<Module>} Set of collected modules.
  175. */
  176. function getAllReferencedModules(compilation, module, type, includeInitial) {
  177. const collectedModules = new Set(includeInitial ? [module] : []);
  178. const visitedModules = new WeakSet([module]);
  179. const stack = [module];
  180. while (stack.length > 0) {
  181. const currentModule = stack.pop();
  182. if (!currentModule) continue;
  183. const outgoingConnections =
  184. compilation.moduleGraph.getOutgoingConnections(currentModule);
  185. if (outgoingConnections) {
  186. for (const connection of outgoingConnections) {
  187. const connectedModule = connection.module;
  188. // Skip if module has already been visited
  189. if (!connectedModule || visitedModules.has(connectedModule)) {
  190. continue;
  191. }
  192. // Handle 'initial' type (skipping async blocks)
  193. if (type === "initial") {
  194. const parentBlock = compilation.moduleGraph.getParentBlock(
  195. /** @type {Dependency} */
  196. (connection.dependency)
  197. );
  198. if (parentBlock instanceof AsyncDependenciesBlock) {
  199. continue;
  200. }
  201. }
  202. // Handle 'external' type (collecting only external modules)
  203. if (type === "external") {
  204. if (connection.module instanceof ExternalModule) {
  205. collectedModules.add(connectedModule);
  206. }
  207. } else {
  208. // Handle 'all' or unspecified types
  209. collectedModules.add(connectedModule);
  210. }
  211. // Add connected module to the stack and mark it as visited
  212. visitedModules.add(connectedModule);
  213. stack.push(connectedModule);
  214. }
  215. }
  216. }
  217. return collectedModules;
  218. }
  219. module.exports = HoistContainerReferences;