StartupChunkDependenciesRuntimeModule.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const RuntimeGlobals = require("../RuntimeGlobals");
  7. const RuntimeModule = require("../RuntimeModule");
  8. const Template = require("../Template");
  9. /** @typedef {import("../Chunk")} Chunk */
  10. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  11. /** @typedef {import("../Compilation")} Compilation */
  12. class StartupChunkDependenciesRuntimeModule extends RuntimeModule {
  13. /**
  14. * @param {boolean} asyncChunkLoading use async chunk loading
  15. */
  16. constructor(asyncChunkLoading) {
  17. super("startup chunk dependencies", RuntimeModule.STAGE_TRIGGER);
  18. this.asyncChunkLoading = asyncChunkLoading;
  19. }
  20. /**
  21. * @returns {string | null} runtime code
  22. */
  23. generate() {
  24. const chunkGraph = /** @type {ChunkGraph} */ (this.chunkGraph);
  25. const chunk = /** @type {Chunk} */ (this.chunk);
  26. const chunkIds = [
  27. ...chunkGraph.getChunkEntryDependentChunksIterable(chunk)
  28. ].map(chunk => chunk.id);
  29. const compilation = /** @type {Compilation} */ (this.compilation);
  30. const { runtimeTemplate } = compilation;
  31. return Template.asString([
  32. `var next = ${RuntimeGlobals.startup};`,
  33. `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction(
  34. "",
  35. !this.asyncChunkLoading
  36. ? [
  37. ...chunkIds.map(
  38. id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});`
  39. ),
  40. "return next();"
  41. ]
  42. : chunkIds.length === 1
  43. ? `return ${RuntimeGlobals.ensureChunk}(${JSON.stringify(
  44. chunkIds[0]
  45. )}).then(next);`
  46. : chunkIds.length > 2
  47. ? [
  48. // using map is shorter for 3 or more chunks
  49. `return Promise.all(${JSON.stringify(chunkIds)}.map(${
  50. RuntimeGlobals.ensureChunk
  51. }, ${RuntimeGlobals.require})).then(next);`
  52. ]
  53. : [
  54. // calling ensureChunk directly is shorter for 0 - 2 chunks
  55. "return Promise.all([",
  56. Template.indent(
  57. chunkIds
  58. .map(
  59. id =>
  60. `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)})`
  61. )
  62. .join(",\n")
  63. ),
  64. "]).then(next);"
  65. ]
  66. )};`
  67. ]);
  68. }
  69. }
  70. module.exports = StartupChunkDependenciesRuntimeModule;