ChunkPrefetchStartupRuntimeModule.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. /** @typedef {import("../Chunk")} Chunk */
  9. /** @typedef {import("../Chunk").ChunkChildOfTypeInOrder} ChunkChildOfTypeInOrder */
  10. /** @typedef {import("../Compilation")} Compilation */
  11. class ChunkPrefetchStartupRuntimeModule extends RuntimeModule {
  12. /**
  13. * @param {ChunkChildOfTypeInOrder[]} startupChunks chunk ids to trigger when chunks are loaded
  14. */
  15. constructor(startupChunks) {
  16. super("startup prefetch", RuntimeModule.STAGE_TRIGGER);
  17. /** @type {ChunkChildOfTypeInOrder[]} */
  18. this.startupChunks = startupChunks;
  19. }
  20. /**
  21. * Generates runtime code for this runtime module.
  22. * @returns {string | null} runtime code
  23. */
  24. generate() {
  25. const { startupChunks } = this;
  26. const compilation = /** @type {Compilation} */ (this.compilation);
  27. const chunk = /** @type {Chunk} */ (this.chunk);
  28. const { runtimeTemplate } = compilation;
  29. return Template.asString(
  30. startupChunks.map(
  31. ({ onChunks, chunks }) =>
  32. `${RuntimeGlobals.onChunksLoaded}(0, ${JSON.stringify(
  33. // This need to include itself to delay execution after this chunk has been fully loaded
  34. onChunks.filter((c) => c === chunk).map((c) => c.id)
  35. )}, ${runtimeTemplate.basicFunction(
  36. "",
  37. chunks.size < 3
  38. ? Array.from(
  39. chunks,
  40. (c) =>
  41. `${RuntimeGlobals.prefetchChunk}(${JSON.stringify(c.id)});`
  42. )
  43. : `${JSON.stringify(Array.from(chunks, (c) => c.id))}.map(${
  44. RuntimeGlobals.prefetchChunk
  45. });`
  46. )}, 5);`
  47. )
  48. );
  49. }
  50. }
  51. module.exports = ChunkPrefetchStartupRuntimeModule;