StartupChunkDependenciesRuntimeModule.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. class StartupChunkDependenciesRuntimeModule extends RuntimeModule {
  10. constructor(asyncChunkLoading) {
  11. super("startup chunk dependencies", RuntimeModule.STAGE_TRIGGER);
  12. this.asyncChunkLoading = asyncChunkLoading;
  13. }
  14. /**
  15. * @returns {string} runtime code
  16. */
  17. generate() {
  18. const { chunkGraph, chunk, compilation } = this;
  19. const { runtimeTemplate } = compilation;
  20. const chunkIds = Array.from(
  21. chunkGraph.getChunkEntryDependentChunksIterable(chunk)
  22. ).map(chunk => {
  23. return chunk.id;
  24. });
  25. return Template.asString([
  26. `var next = ${RuntimeGlobals.startup};`,
  27. `${RuntimeGlobals.startup} = ${runtimeTemplate.basicFunction(
  28. "",
  29. !this.asyncChunkLoading
  30. ? chunkIds
  31. .map(
  32. id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)});`
  33. )
  34. .concat("return next();")
  35. : chunkIds.length === 1
  36. ? `return ${RuntimeGlobals.ensureChunk}(${JSON.stringify(
  37. chunkIds[0]
  38. )}).then(next);`
  39. : chunkIds.length > 2
  40. ? [
  41. // using map is shorter for 3 or more chunks
  42. `return Promise.all(${JSON.stringify(chunkIds)}.map(${
  43. RuntimeGlobals.ensureChunk
  44. }, __webpack_require__)).then(next);`
  45. ]
  46. : [
  47. // calling ensureChunk directly is shorter for 0 - 2 chunks
  48. "return Promise.all([",
  49. Template.indent(
  50. chunkIds
  51. .map(
  52. id => `${RuntimeGlobals.ensureChunk}(${JSON.stringify(id)})`
  53. )
  54. .join(",\n")
  55. ),
  56. "]).then(next);"
  57. ]
  58. )};`
  59. ]);
  60. }
  61. }
  62. module.exports = StartupChunkDependenciesRuntimeModule;