webpack/lib/async-modules/AwaitDependenciesInitFragme...

74 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-06-05 20:17:15 +08:00
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const InitFragment = require("../InitFragment");
const RuntimeGlobals = require("../RuntimeGlobals");
2021-01-29 18:12:11 +08:00
const Template = require("../Template");
2019-06-05 20:17:15 +08:00
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
2019-06-05 20:17:15 +08:00
/**
2024-03-18 01:15:44 +08:00
* @extends {InitFragment<GenerateContext>}
*/
2019-06-05 20:17:15 +08:00
class AwaitDependenciesInitFragment extends InitFragment {
/**
* @param {Set<string>} promises the promises that should be awaited
2019-06-05 20:17:15 +08:00
*/
constructor(promises) {
super(
undefined,
2019-06-05 20:17:15 +08:00
InitFragment.STAGE_ASYNC_DEPENDENCIES,
0,
"await-dependencies"
);
this.promises = promises;
}
2023-06-17 01:13:03 +08:00
/**
* @param {AwaitDependenciesInitFragment} other other AwaitDependenciesInitFragment
* @returns {AwaitDependenciesInitFragment} AwaitDependenciesInitFragment
*/
2019-06-05 20:17:15 +08:00
merge(other) {
const promises = new Set(other.promises);
for (const p of this.promises) {
promises.add(p);
}
return new AwaitDependenciesInitFragment(promises);
}
/**
2024-01-27 00:17:45 +08:00
* @param {GenerateContext} context context
2024-03-18 23:28:40 +08:00
* @returns {string | Source | undefined} the source code that will be included as initialization code
*/
getContent({ runtimeRequirements }) {
runtimeRequirements.add(RuntimeGlobals.module);
const promises = this.promises;
if (promises.size === 0) {
return "";
}
if (promises.size === 1) {
for (const p of promises) {
2021-01-29 18:12:11 +08:00
return Template.asString([
`var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${p}]);`,
`${p} = (__webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__)[0];`,
2021-01-29 18:12:11 +08:00
""
]);
}
}
const sepPromises = Array.from(promises).join(", ");
2021-01-29 18:12:11 +08:00
// TODO check if destructuring is supported
return Template.asString([
`var __webpack_async_dependencies__ = __webpack_handle_async_dependencies__([${sepPromises}]);`,
`([${sepPromises}] = __webpack_async_dependencies__.then ? (await __webpack_async_dependencies__)() : __webpack_async_dependencies__);`,
2021-01-29 18:12:11 +08:00
""
]);
2019-06-05 20:17:15 +08:00
}
}
module.exports = AwaitDependenciesInitFragment;