ChunkPrefetchFunctionRuntimeModule.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const RuntimeModule = require("../RuntimeModule");
  6. const Template = require("../Template");
  7. /** @import Compilation from "../Compilation" */
  8. class ChunkPrefetchFunctionRuntimeModule extends RuntimeModule {
  9. /**
  10. * Returns true, if the runtime module should get it's own scope.
  11. * When false, `generate()` must emit complete statements ending with `;`
  12. * so a following runtime IIFE is not parsed as a call (ASI).
  13. * @returns {boolean} true, if the runtime module should get it's own scope
  14. */
  15. shouldIsolate() {
  16. return false;
  17. }
  18. /**
  19. * @param {"prefetch" | "preload"} type "prefetch" or "preload" chunk type function
  20. * @param {string | null} runtimeFunction the runtime function name, or `null` where nothing fans out over the handlers
  21. * @param {string} runtimeHandlers the runtime handlers
  22. */
  23. constructor(type, runtimeFunction, runtimeHandlers) {
  24. super(`chunk ${type} function`);
  25. /** @type {string | null} */
  26. this.runtimeFunction = runtimeFunction;
  27. /** @type {string} */
  28. this.runtimeHandlers = runtimeHandlers;
  29. }
  30. /**
  31. * Generates runtime code for this runtime module.
  32. * @returns {string | null} runtime code
  33. */
  34. generate() {
  35. const { runtimeFunction, runtimeHandlers } = this;
  36. const compilation = /** @type {Compilation} */ (this.compilation);
  37. const { runtimeTemplate } = compilation;
  38. return Template.asString([
  39. `${runtimeHandlers} = {};`,
  40. ...(runtimeFunction === null
  41. ? []
  42. : [
  43. `${runtimeFunction} = ${runtimeTemplate.basicFunction("chunkId", [
  44. // map is shorter than forEach
  45. `Object.keys(${runtimeHandlers}).map(${runtimeTemplate.basicFunction(
  46. "key",
  47. `${runtimeHandlers}[key](chunkId);`
  48. )});`
  49. ])};`
  50. ])
  51. ]);
  52. }
  53. }
  54. module.exports = ChunkPrefetchFunctionRuntimeModule;