AwaitDependenciesInitFragment.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const InitFragment = require("../InitFragment");
  7. const RuntimeGlobals = require("../RuntimeGlobals");
  8. const Template = require("../Template");
  9. /** @typedef {import("webpack-sources").Source} Source */
  10. /** @typedef {import("../Generator").GenerateContext} GenerateContext */
  11. /**
  12. * @extends {InitFragment<GenerateContext>}
  13. */
  14. class AwaitDependenciesInitFragment extends InitFragment {
  15. /**
  16. * @param {Set<string>} promises the promises that should be awaited
  17. */
  18. constructor(promises) {
  19. super(
  20. undefined,
  21. InitFragment.STAGE_ASYNC_DEPENDENCIES,
  22. 0,
  23. "await-dependencies"
  24. );
  25. this.promises = promises;
  26. }
  27. /**
  28. * @param {AwaitDependenciesInitFragment} other other AwaitDependenciesInitFragment
  29. * @returns {AwaitDependenciesInitFragment} AwaitDependenciesInitFragment
  30. */
  31. merge(other) {
  32. const promises = new Set(other.promises);
  33. for (const p of this.promises) {
  34. promises.add(p);
  35. }
  36. return new AwaitDependenciesInitFragment(promises);
  37. }
  38. /**
  39. * @param {GenerateContext} context context
  40. * @returns {string | Source | undefined} the source code that will be included as initialization code
  41. */
  42. getContent({ runtimeRequirements }) {
  43. runtimeRequirements.add(RuntimeGlobals.module);
  44. const promises = this.promises;
  45. if (promises.size === 0) {
  46. return "";
  47. }
  48. if (promises.size === 1) {
  49. for (const p of promises) {
  50. return Template.asString([
  51. `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${p}]);`,
  52. `${p} = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];`,
  53. ""
  54. ]);
  55. }
  56. }
  57. const sepPromises = Array.from(promises).join(", ");
  58. // TODO check if destructuring is supported
  59. return Template.asString([
  60. `var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${sepPromises}]);`,
  61. `([${sepPromises}] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);`,
  62. ""
  63. ]);
  64. }
  65. }
  66. module.exports = AwaitDependenciesInitFragment;