ChunkPrefetchStartupRuntimeModule.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. /** @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. * @returns {string | null} runtime code
  22. */
  23. generate() {
  24. const { startupChunks } = this;
  25. const compilation = /** @type {Compilation} */ (this.compilation);
  26. const chunk = /** @type {Chunk} */ (this.chunk);
  27. const { runtimeTemplate } = compilation;
  28. return Template.asString(
  29. startupChunks.map(
  30. ({ onChunks, chunks }) =>
  31. `${RuntimeGlobals.onChunksLoaded}(0, ${JSON.stringify(
  32. // This need to include itself to delay execution after this chunk has been fully loaded
  33. onChunks.filter((c) => c === chunk).map((c) => c.id)
  34. )}, ${runtimeTemplate.basicFunction(
  35. "",
  36. chunks.size < 3
  37. ? Array.from(
  38. chunks,
  39. (c) =>
  40. `${RuntimeGlobals.prefetchChunk}(${JSON.stringify(c.id)});`
  41. )
  42. : `${JSON.stringify(Array.from(chunks, (c) => c.id))}.map(${
  43. RuntimeGlobals.prefetchChunk
  44. });`
  45. )}, 5);`
  46. )
  47. );
  48. }
  49. }
  50. module.exports = ChunkPrefetchStartupRuntimeModule;