ModuleChunkFormatPlugin.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { ConcatSource } = require("webpack-sources");
  7. const { HotUpdateChunk, RuntimeGlobals } = require("..");
  8. const Template = require("../Template");
  9. const {
  10. createChunkHashHandler,
  11. getChunkInfo
  12. } = require("../javascript/ChunkFormatHelpers");
  13. const { getAllChunks } = require("../javascript/ChunkHelpers");
  14. const {
  15. chunkHasJs,
  16. getChunkFilenameTemplate,
  17. getCompilationHooks
  18. } = require("../javascript/JavascriptModulesPlugin");
  19. const { getUndoPath } = require("../util/identifier");
  20. /** @typedef {import("webpack-sources").Source} Source */
  21. /** @typedef {import("../Chunk")} Chunk */
  22. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  23. /** @typedef {import("../ChunkGroup")} ChunkGroup */
  24. /** @typedef {import("../Compilation")} Compilation */
  25. /** @typedef {import("../Compiler")} Compiler */
  26. /** @typedef {import("../Entrypoint")} Entrypoint */
  27. /** @typedef {import("../Module")} Module */
  28. /** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
  29. /**
  30. * @param {Compilation} compilation the compilation instance
  31. * @param {Chunk} chunk the chunk
  32. * @param {Chunk} runtimeChunk the runtime chunk
  33. * @returns {string} the relative path
  34. */
  35. const getRelativePath = (compilation, chunk, runtimeChunk) => {
  36. const currentOutputName = compilation
  37. .getPath(
  38. getChunkFilenameTemplate(runtimeChunk, compilation.outputOptions),
  39. {
  40. chunk: runtimeChunk,
  41. contentHashType: "javascript"
  42. }
  43. )
  44. .replace(/^\/+/g, "")
  45. .split("/");
  46. const baseOutputName = [...currentOutputName];
  47. const chunkOutputName = compilation
  48. .getPath(getChunkFilenameTemplate(chunk, compilation.outputOptions), {
  49. chunk,
  50. contentHashType: "javascript"
  51. })
  52. .replace(/^\/+/g, "")
  53. .split("/");
  54. // remove common parts except filename
  55. while (
  56. baseOutputName.length > 1 &&
  57. chunkOutputName.length > 1 &&
  58. baseOutputName[0] === chunkOutputName[0]
  59. ) {
  60. baseOutputName.shift();
  61. chunkOutputName.shift();
  62. }
  63. const last = chunkOutputName.join("/");
  64. // create final path
  65. return getUndoPath(baseOutputName.join("/"), last, true) + last;
  66. };
  67. /**
  68. * @param {Compilation} compilation the compilation instance
  69. * @param {Chunk} chunk the chunk to render the import for
  70. * @param {string=} namedImport the named import to use for the import
  71. * @param {Chunk=} runtimeChunk the runtime chunk
  72. * @returns {string} the import source
  73. */
  74. function renderChunkImport(compilation, chunk, namedImport, runtimeChunk) {
  75. return `import ${namedImport ? `* as ${namedImport}` : `{ ${RuntimeGlobals.require} }`} from ${JSON.stringify(
  76. getRelativePath(compilation, chunk, runtimeChunk || chunk)
  77. )};\n`;
  78. }
  79. /**
  80. * @param {number} index the index of the chunk
  81. * @returns {string} the named import to use for the import
  82. */
  83. function getChunkNamedImport(index) {
  84. return `__webpack_chunk_${index}__`;
  85. }
  86. const PLUGIN_NAME = "ModuleChunkFormatPlugin";
  87. class ModuleChunkFormatPlugin {
  88. /**
  89. * Apply the plugin
  90. * @param {Compiler} compiler the compiler instance
  91. * @returns {void}
  92. */
  93. apply(compiler) {
  94. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => {
  95. compilation.hooks.additionalChunkRuntimeRequirements.tap(
  96. PLUGIN_NAME,
  97. (chunk, set) => {
  98. if (chunk.hasRuntime()) return;
  99. if (compilation.chunkGraph.getNumberOfEntryModules(chunk) > 0) {
  100. set.add(RuntimeGlobals.require);
  101. set.add(RuntimeGlobals.externalInstallChunk);
  102. }
  103. }
  104. );
  105. const hooks = getCompilationHooks(compilation);
  106. /**
  107. * @param {Set<Chunk>} chunks the chunks to render
  108. * @param {ChunkGraph} chunkGraph the chunk graph
  109. * @param {Chunk=} runtimeChunk the runtime chunk
  110. * @returns {Source|undefined} the source
  111. */
  112. const withDependentChunks = (chunks, chunkGraph, runtimeChunk) => {
  113. if (/** @type {Set<Chunk>} */ (chunks).size > 0) {
  114. const source = new ConcatSource();
  115. let index = 0;
  116. for (const chunk of chunks) {
  117. index++;
  118. if (!chunkHasJs(chunk, chunkGraph)) {
  119. continue;
  120. }
  121. const namedImport = getChunkNamedImport(index);
  122. source.add(
  123. renderChunkImport(
  124. compilation,
  125. chunk,
  126. namedImport,
  127. runtimeChunk || chunk
  128. )
  129. );
  130. source.add(
  131. `${RuntimeGlobals.externalInstallChunk}(${namedImport});\n`
  132. );
  133. }
  134. return source;
  135. }
  136. };
  137. hooks.renderStartup.tap(
  138. PLUGIN_NAME,
  139. (modules, _lastModule, renderContext) => {
  140. const { chunk, chunkGraph } = renderContext;
  141. if (
  142. chunkGraph.getNumberOfEntryModules(chunk) > 0 &&
  143. chunk.hasRuntime()
  144. ) {
  145. const entryDependentChunks =
  146. chunkGraph.getChunkEntryDependentChunksIterable(chunk);
  147. const sourceWithDependentChunks = withDependentChunks(
  148. /** @type {Set<Chunk>} */ (entryDependentChunks),
  149. chunkGraph,
  150. chunk
  151. );
  152. if (!sourceWithDependentChunks) {
  153. return modules;
  154. }
  155. if (modules.size() === 0) {
  156. return sourceWithDependentChunks;
  157. }
  158. const source = new ConcatSource();
  159. source.add(sourceWithDependentChunks);
  160. source.add("\n");
  161. source.add(modules);
  162. return source;
  163. }
  164. return modules;
  165. }
  166. );
  167. hooks.renderChunk.tap(PLUGIN_NAME, (modules, renderContext) => {
  168. const { chunk, chunkGraph, runtimeTemplate } = renderContext;
  169. const hotUpdateChunk = chunk instanceof HotUpdateChunk ? chunk : null;
  170. const source = new ConcatSource();
  171. source.add(
  172. `export const ${RuntimeGlobals.esmId} = ${JSON.stringify(chunk.id)};\n`
  173. );
  174. source.add(
  175. `export const ${RuntimeGlobals.esmIds} = ${JSON.stringify(chunk.ids)};\n`
  176. );
  177. source.add(`export const ${RuntimeGlobals.esmModules} = `);
  178. source.add(modules);
  179. source.add(";\n");
  180. const runtimeModules = chunkGraph.getChunkRuntimeModulesInOrder(chunk);
  181. if (runtimeModules.length > 0) {
  182. source.add(`export const ${RuntimeGlobals.esmRuntime} =\n`);
  183. source.add(
  184. Template.renderChunkRuntimeModules(runtimeModules, renderContext)
  185. );
  186. }
  187. if (hotUpdateChunk) {
  188. return source;
  189. }
  190. const { entries, runtimeChunk } = getChunkInfo(chunk, chunkGraph);
  191. if (runtimeChunk) {
  192. const entrySource = new ConcatSource();
  193. entrySource.add(source);
  194. entrySource.add(";\n\n// load runtime\n");
  195. entrySource.add(
  196. renderChunkImport(compilation, runtimeChunk, "", chunk)
  197. );
  198. const startupSource = new ConcatSource();
  199. startupSource.add(
  200. `var __webpack_exec__ = ${runtimeTemplate.returningFunction(
  201. `${RuntimeGlobals.require}(${RuntimeGlobals.entryModuleId} = moduleId)`,
  202. "moduleId"
  203. )}\n`
  204. );
  205. const loadedChunks = new Set();
  206. for (let i = 0; i < entries.length; i++) {
  207. const [module, entrypoint] = entries[i];
  208. if (!chunkGraph.getModuleSourceTypes(module).has("javascript")) {
  209. continue;
  210. }
  211. const final = i + 1 === entries.length;
  212. const moduleId = chunkGraph.getModuleId(module);
  213. const chunks = getAllChunks(
  214. /** @type {Entrypoint} */ (entrypoint),
  215. /** @type {Chunk} */ (runtimeChunk),
  216. undefined
  217. );
  218. const processChunks = new Set();
  219. for (const _chunk of chunks) {
  220. if (loadedChunks.has(_chunk)) {
  221. continue;
  222. }
  223. loadedChunks.add(_chunk);
  224. processChunks.add(_chunk);
  225. }
  226. const sourceWithDependentChunks = withDependentChunks(
  227. processChunks,
  228. chunkGraph,
  229. chunk
  230. );
  231. if (sourceWithDependentChunks) {
  232. startupSource.add("\n");
  233. startupSource.add(sourceWithDependentChunks);
  234. }
  235. startupSource.add(
  236. `${
  237. final ? `var ${RuntimeGlobals.exports} = ` : ""
  238. }__webpack_exec__(${JSON.stringify(moduleId)});\n`
  239. );
  240. }
  241. entrySource.add(
  242. hooks.renderStartup.call(
  243. startupSource,
  244. entries[entries.length - 1][0],
  245. {
  246. ...renderContext,
  247. inlined: false
  248. }
  249. )
  250. );
  251. return entrySource;
  252. }
  253. return source;
  254. });
  255. hooks.chunkHash.tap(PLUGIN_NAME, createChunkHashHandler(PLUGIN_NAME));
  256. });
  257. }
  258. }
  259. module.exports = ModuleChunkFormatPlugin;