ChunkPrefetchStartupRuntimeModule.js 1.6 KB

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