StartupEntrypointRuntimeModule.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 { entryModuleIdExpression } = require("../javascript/StartupHelpers");
  8. /** @import Chunk from "../Chunk" */
  9. /** @import Compilation from "../Compilation" */
  10. class StartupEntrypointRuntimeModule extends RuntimeModule {
  11. /**
  12. * Returns true, if the runtime module should get it's own scope.
  13. * When false, `generate()` must emit complete statements ending with `;`
  14. * so a following runtime IIFE is not parsed as a call (ASI).
  15. * @returns {boolean} true, if the runtime module should get it's own scope
  16. */
  17. shouldIsolate() {
  18. return false;
  19. }
  20. /**
  21. * @param {boolean} asyncChunkLoading use async chunk loading
  22. */
  23. constructor(asyncChunkLoading) {
  24. super("startup entrypoint");
  25. /** @type {boolean} */
  26. this.asyncChunkLoading = asyncChunkLoading;
  27. }
  28. /**
  29. * Generates runtime code for this runtime module.
  30. * @returns {string | null} runtime code
  31. */
  32. generate() {
  33. const compilation = /** @type {Compilation} */ (this.compilation);
  34. const { runtimeTemplate, chunkGraph } = compilation;
  35. const chunk = /** @type {Chunk} */ (this.chunk);
  36. const cst = runtimeTemplate.renderConst();
  37. return `${
  38. RuntimeGlobals.startupEntrypoint
  39. } = ${runtimeTemplate.basicFunction("result, chunkIds, fn", [
  40. "// arguments: chunkIds, moduleId are deprecated",
  41. `${cst} moduleId = chunkIds;`,
  42. `if(!fn) chunkIds = result, fn = ${runtimeTemplate.returningFunction(
  43. `${RuntimeGlobals.require}(${entryModuleIdExpression(
  44. chunkGraph,
  45. chunk,
  46. "moduleId"
  47. )})`
  48. )};`,
  49. ...(this.asyncChunkLoading
  50. ? [
  51. `return Promise.all(chunkIds.map(${RuntimeGlobals.ensureChunk}, ${
  52. RuntimeGlobals.require
  53. })).then(${runtimeTemplate.basicFunction("", [
  54. `${cst} r = fn();`,
  55. "return r === undefined ? result : r;"
  56. ])})`
  57. ]
  58. : [
  59. `chunkIds.map(${RuntimeGlobals.ensureChunk}, ${RuntimeGlobals.require})`,
  60. `${cst} r = fn();`,
  61. "return r === undefined ? result : r;"
  62. ])
  63. ])};`;
  64. }
  65. }
  66. module.exports = StartupEntrypointRuntimeModule;