ModuleChunkLoadingRuntimeModule.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const { SyncWaterfallHook } = require("tapable");
  6. const Compilation = require("../Compilation");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const RuntimeModule = require("../RuntimeModule");
  9. const Template = require("../Template");
  10. const {
  11. getChunkFilenameTemplate,
  12. chunkHasJs
  13. } = require("../javascript/JavascriptModulesPlugin");
  14. const { getInitialChunkIds } = require("../javascript/StartupHelpers");
  15. const compileBooleanMatcher = require("../util/compileBooleanMatcher");
  16. const { getUndoPath } = require("../util/identifier");
  17. /** @typedef {import("../../declarations/WebpackOptions").Environment} Environment */
  18. /** @typedef {import("../Chunk")} Chunk */
  19. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  20. /** @typedef {import("../Module").ReadOnlyRuntimeRequirements} ReadOnlyRuntimeRequirements */
  21. /**
  22. * @typedef {object} JsonpCompilationPluginHooks
  23. * @property {SyncWaterfallHook<[string, Chunk]>} linkPreload
  24. * @property {SyncWaterfallHook<[string, Chunk]>} linkPrefetch
  25. */
  26. /** @type {WeakMap<Compilation, JsonpCompilationPluginHooks>} */
  27. const compilationHooksMap = new WeakMap();
  28. class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
  29. /**
  30. * @param {Compilation} compilation the compilation
  31. * @returns {JsonpCompilationPluginHooks} hooks
  32. */
  33. static getCompilationHooks(compilation) {
  34. if (!(compilation instanceof Compilation)) {
  35. throw new TypeError(
  36. "The 'compilation' argument must be an instance of Compilation"
  37. );
  38. }
  39. let hooks = compilationHooksMap.get(compilation);
  40. if (hooks === undefined) {
  41. hooks = {
  42. linkPreload: new SyncWaterfallHook(["source", "chunk"]),
  43. linkPrefetch: new SyncWaterfallHook(["source", "chunk"])
  44. };
  45. compilationHooksMap.set(compilation, hooks);
  46. }
  47. return hooks;
  48. }
  49. /**
  50. * @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
  51. */
  52. constructor(runtimeRequirements) {
  53. super("import chunk loading", RuntimeModule.STAGE_ATTACH);
  54. this._runtimeRequirements = runtimeRequirements;
  55. }
  56. /**
  57. * @private
  58. * @param {Chunk} chunk chunk
  59. * @param {string} rootOutputDir root output directory
  60. * @returns {string} generated code
  61. */
  62. _generateBaseUri(chunk, rootOutputDir) {
  63. const options = chunk.getEntryOptions();
  64. if (options && options.baseUri) {
  65. return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
  66. }
  67. const compilation = /** @type {Compilation} */ (this.compilation);
  68. const {
  69. outputOptions: { importMetaName }
  70. } = compilation;
  71. return `${RuntimeGlobals.baseURI} = new URL(${JSON.stringify(
  72. rootOutputDir
  73. )}, ${importMetaName}.url);`;
  74. }
  75. /**
  76. * @returns {string | null} runtime code
  77. */
  78. generate() {
  79. const compilation = /** @type {Compilation} */ (this.compilation);
  80. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  81. const chunk = /** @type {Chunk} */ (this.chunk);
  82. const environment =
  83. /** @type {Environment} */
  84. (compilation.outputOptions.environment);
  85. const {
  86. runtimeTemplate,
  87. outputOptions: { importFunctionName, crossOriginLoading }
  88. } = compilation;
  89. const fn = RuntimeGlobals.ensureChunkHandlers;
  90. const withBaseURI = this._runtimeRequirements.has(RuntimeGlobals.baseURI);
  91. const withExternalInstallChunk = this._runtimeRequirements.has(
  92. RuntimeGlobals.externalInstallChunk
  93. );
  94. const withLoading = this._runtimeRequirements.has(
  95. RuntimeGlobals.ensureChunkHandlers
  96. );
  97. const withOnChunkLoad = this._runtimeRequirements.has(
  98. RuntimeGlobals.onChunksLoaded
  99. );
  100. const withHmr = this._runtimeRequirements.has(
  101. RuntimeGlobals.hmrDownloadUpdateHandlers
  102. );
  103. const { linkPreload, linkPrefetch } =
  104. ModuleChunkLoadingRuntimeModule.getCompilationHooks(compilation);
  105. const isNeutralPlatform = runtimeTemplate.isNeutralPlatform();
  106. const withPrefetch =
  107. (environment.document || isNeutralPlatform) &&
  108. this._runtimeRequirements.has(RuntimeGlobals.prefetchChunkHandlers) &&
  109. chunk.hasChildByOrder(chunkGraph, "prefetch", true, chunkHasJs);
  110. const withPreload =
  111. (environment.document || isNeutralPlatform) &&
  112. this._runtimeRequirements.has(RuntimeGlobals.preloadChunkHandlers) &&
  113. chunk.hasChildByOrder(chunkGraph, "preload", true, chunkHasJs);
  114. const conditionMap = chunkGraph.getChunkConditionMap(chunk, chunkHasJs);
  115. const hasJsMatcher = compileBooleanMatcher(conditionMap);
  116. const initialChunkIds = getInitialChunkIds(chunk, chunkGraph, chunkHasJs);
  117. const outputName = compilation.getPath(
  118. getChunkFilenameTemplate(chunk, compilation.outputOptions),
  119. {
  120. chunk,
  121. contentHashType: "javascript"
  122. }
  123. );
  124. const rootOutputDir = getUndoPath(
  125. outputName,
  126. /** @type {string} */ (compilation.outputOptions.path),
  127. true
  128. );
  129. const stateExpression = withHmr
  130. ? `${RuntimeGlobals.hmrRuntimeStatePrefix}_module`
  131. : undefined;
  132. return Template.asString([
  133. withBaseURI
  134. ? this._generateBaseUri(chunk, rootOutputDir)
  135. : "// no baseURI",
  136. "",
  137. "// object to store loaded and loading chunks",
  138. "// undefined = chunk not loaded, null = chunk preloaded/prefetched",
  139. "// [resolve, Promise] = chunk loading, 0 = chunk loaded",
  140. `var installedChunks = ${
  141. stateExpression ? `${stateExpression} = ${stateExpression} || ` : ""
  142. }{`,
  143. Template.indent(
  144. Array.from(initialChunkIds, id => `${JSON.stringify(id)}: 0`).join(
  145. ",\n"
  146. )
  147. ),
  148. "};",
  149. "",
  150. withLoading || withExternalInstallChunk
  151. ? `var installChunk = ${runtimeTemplate.basicFunction("data", [
  152. runtimeTemplate.destructureObject(
  153. ["__webpack_ids__", "__webpack_modules__", "__webpack_runtime__"],
  154. "data"
  155. ),
  156. '// add "modules" to the modules object,',
  157. '// then flag all "ids" as loaded and fire callback',
  158. "var moduleId, chunkId, i = 0;",
  159. "for(moduleId in __webpack_modules__) {",
  160. Template.indent([
  161. `if(${RuntimeGlobals.hasOwnProperty}(__webpack_modules__, moduleId)) {`,
  162. Template.indent(
  163. `${RuntimeGlobals.moduleFactories}[moduleId] = __webpack_modules__[moduleId];`
  164. ),
  165. "}"
  166. ]),
  167. "}",
  168. `if(__webpack_runtime__) __webpack_runtime__(${RuntimeGlobals.require});`,
  169. "for(;i < __webpack_ids__.length; i++) {",
  170. Template.indent([
  171. "chunkId = __webpack_ids__[i];",
  172. `if(${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) && installedChunks[chunkId]) {`,
  173. Template.indent("installedChunks[chunkId][0]();"),
  174. "}",
  175. "installedChunks[__webpack_ids__[i]] = 0;"
  176. ]),
  177. "}",
  178. withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : ""
  179. ])}`
  180. : "// no install chunk",
  181. "",
  182. withLoading
  183. ? Template.asString([
  184. `${fn}.j = ${runtimeTemplate.basicFunction(
  185. "chunkId, promises",
  186. hasJsMatcher !== false
  187. ? Template.indent([
  188. "// import() chunk loading for javascript",
  189. `var installedChunkData = ${RuntimeGlobals.hasOwnProperty}(installedChunks, chunkId) ? installedChunks[chunkId] : undefined;`,
  190. 'if(installedChunkData !== 0) { // 0 means "already installed".',
  191. Template.indent([
  192. "",
  193. '// a Promise means "currently loading".',
  194. "if(installedChunkData) {",
  195. Template.indent([
  196. "promises.push(installedChunkData[1]);"
  197. ]),
  198. "} else {",
  199. Template.indent([
  200. hasJsMatcher === true
  201. ? "if(true) { // all chunks have JS"
  202. : `if(${hasJsMatcher("chunkId")}) {`,
  203. Template.indent([
  204. "// setup Promise in chunk cache",
  205. `var promise = ${importFunctionName}(${JSON.stringify(
  206. rootOutputDir
  207. )} + ${
  208. RuntimeGlobals.getChunkScriptFilename
  209. }(chunkId)).then(installChunk, ${runtimeTemplate.basicFunction(
  210. "e",
  211. [
  212. "if(installedChunks[chunkId] !== 0) installedChunks[chunkId] = undefined;",
  213. "throw e;"
  214. ]
  215. )});`,
  216. `var promise = Promise.race([promise, new Promise(${runtimeTemplate.expressionFunction(
  217. "installedChunkData = installedChunks[chunkId] = [resolve]",
  218. "resolve"
  219. )})])`,
  220. "promises.push(installedChunkData[1] = promise);"
  221. ]),
  222. hasJsMatcher === true
  223. ? "}"
  224. : "} else installedChunks[chunkId] = 0;"
  225. ]),
  226. "}"
  227. ]),
  228. "}"
  229. ])
  230. : Template.indent(["installedChunks[chunkId] = 0;"])
  231. )};`
  232. ])
  233. : "// no chunk on demand loading",
  234. "",
  235. withPrefetch && hasJsMatcher !== false
  236. ? `${
  237. RuntimeGlobals.prefetchChunkHandlers
  238. }.j = ${runtimeTemplate.basicFunction("chunkId", [
  239. `if((!${
  240. RuntimeGlobals.hasOwnProperty
  241. }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
  242. hasJsMatcher === true ? "true" : hasJsMatcher("chunkId")
  243. }) {`,
  244. Template.indent([
  245. "installedChunks[chunkId] = null;",
  246. isNeutralPlatform
  247. ? "if (typeof document === 'undefined') return;"
  248. : "",
  249. linkPrefetch.call(
  250. Template.asString([
  251. "var link = document.createElement('link');",
  252. crossOriginLoading
  253. ? `link.crossOrigin = ${JSON.stringify(
  254. crossOriginLoading
  255. )};`
  256. : "",
  257. `if (${RuntimeGlobals.scriptNonce}) {`,
  258. Template.indent(
  259. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  260. ),
  261. "}",
  262. 'link.rel = "prefetch";',
  263. 'link.as = "script";',
  264. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`
  265. ]),
  266. chunk
  267. ),
  268. "document.head.appendChild(link);"
  269. ]),
  270. "}"
  271. ])};`
  272. : "// no prefetching",
  273. "",
  274. withPreload && hasJsMatcher !== false
  275. ? `${
  276. RuntimeGlobals.preloadChunkHandlers
  277. }.j = ${runtimeTemplate.basicFunction("chunkId", [
  278. `if((!${
  279. RuntimeGlobals.hasOwnProperty
  280. }(installedChunks, chunkId) || installedChunks[chunkId] === undefined) && ${
  281. hasJsMatcher === true ? "true" : hasJsMatcher("chunkId")
  282. }) {`,
  283. Template.indent([
  284. "installedChunks[chunkId] = null;",
  285. isNeutralPlatform
  286. ? "if (typeof document === 'undefined') return;"
  287. : "",
  288. linkPreload.call(
  289. Template.asString([
  290. "var link = document.createElement('link');",
  291. "link.charset = 'utf-8';",
  292. `if (${RuntimeGlobals.scriptNonce}) {`,
  293. Template.indent(
  294. `link.setAttribute("nonce", ${RuntimeGlobals.scriptNonce});`
  295. ),
  296. "}",
  297. 'link.rel = "modulepreload";',
  298. `link.href = ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);`,
  299. crossOriginLoading
  300. ? crossOriginLoading === "use-credentials"
  301. ? 'link.crossOrigin = "use-credentials";'
  302. : Template.asString([
  303. "if (link.href.indexOf(window.location.origin + '/') !== 0) {",
  304. Template.indent(
  305. `link.crossOrigin = ${JSON.stringify(
  306. crossOriginLoading
  307. )};`
  308. ),
  309. "}"
  310. ])
  311. : ""
  312. ]),
  313. chunk
  314. ),
  315. "document.head.appendChild(link);"
  316. ]),
  317. "}"
  318. ])};`
  319. : "// no preloaded",
  320. "",
  321. withExternalInstallChunk
  322. ? Template.asString([
  323. `${RuntimeGlobals.externalInstallChunk} = installChunk;`
  324. ])
  325. : "// no external install chunk",
  326. "",
  327. withOnChunkLoad
  328. ? `${
  329. RuntimeGlobals.onChunksLoaded
  330. }.j = ${runtimeTemplate.returningFunction(
  331. "installedChunks[chunkId] === 0",
  332. "chunkId"
  333. )};`
  334. : "// no on chunks loaded"
  335. ]);
  336. }
  337. }
  338. module.exports = ModuleChunkLoadingRuntimeModule;