ChunkPrefetchTriggerRuntimeModule.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const RuntimeGlobals = require("../RuntimeGlobals");
  6. const RuntimeModule = require("../RuntimeModule");
  7. const Template = require("../Template");
  8. /** @import Compilation from "../Compilation" */
  9. /** @import { ChunkChildIdsByOrdersMap } from "../Chunk" */
  10. class ChunkPrefetchTriggerRuntimeModule extends RuntimeModule {
  11. /**
  12. * @param {ChunkChildIdsByOrdersMap} chunkMap map from chunk to
  13. */
  14. constructor(chunkMap) {
  15. super("chunk prefetch trigger", RuntimeModule.STAGE_TRIGGER);
  16. /** @type {ChunkChildIdsByOrdersMap} */
  17. this.chunkMap = chunkMap;
  18. }
  19. /**
  20. * Generates runtime code for this runtime module.
  21. * @returns {string | null} runtime code
  22. */
  23. generate() {
  24. const { chunkMap } = this;
  25. const compilation = /** @type {Compilation} */ (this.compilation);
  26. const { runtimeTemplate } = compilation;
  27. const body = [
  28. "var chunks = chunkToChildrenMap[chunkId];",
  29. `Array.isArray(chunks) && chunks.map(${RuntimeGlobals.prefetchChunk});`
  30. ];
  31. return Template.asString([
  32. Template.asString([
  33. `var chunkToChildrenMap = ${JSON.stringify(chunkMap, null, "\t")};`,
  34. `${
  35. RuntimeGlobals.ensureChunkHandlers
  36. }.prefetch = ${runtimeTemplate.expressionFunction(
  37. // Prefetch is best-effort; silence rejections so a failed chunk
  38. // load (e.g. chunkLoadTimeout) doesn't surface as an unhandled
  39. // rejection through this dangling Promise.all chain.
  40. `Promise.all(promises).then(${runtimeTemplate.basicFunction(
  41. "",
  42. body
  43. )}, ${runtimeTemplate.basicFunction("", "")})`,
  44. "chunkId, promises"
  45. )};`
  46. ])
  47. ]);
  48. }
  49. }
  50. module.exports = ChunkPrefetchTriggerRuntimeModule;