ChunkPrefetchStartupRuntimeModule.js 1.5 KB

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