HarmonyAcceptDependency.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Template = require("../Template");
  7. const AwaitDependenciesInitFragment = require("../async-modules/AwaitDependenciesInitFragment");
  8. const makeSerializable = require("../util/makeSerializable");
  9. const HarmonyImportDependency = require("./HarmonyImportDependency");
  10. const { ImportPhaseUtils } = require("./ImportPhase");
  11. const NullDependency = require("./NullDependency");
  12. /** @import { ReplaceSource } from "webpack-sources" */
  13. /** @import Dependency from "../Dependency" */
  14. /** @import { DependencyTemplateContext } from "../DependencyTemplate" */
  15. /** @import { Range } from "../javascript/JavascriptParser" */
  16. /** @import HarmonyAcceptImportDependency from "./HarmonyAcceptImportDependency" */
  17. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext<[Range, HarmonyAcceptImportDependency[], boolean]>} ObjectDeserializerContext */
  18. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext<[Range, HarmonyAcceptImportDependency[], boolean]>} ObjectSerializerContext */
  19. class HarmonyAcceptDependency extends NullDependency {
  20. /**
  21. * Creates an instance of HarmonyAcceptDependency.
  22. * @param {Range} range expression range
  23. * @param {HarmonyAcceptImportDependency[]} dependencies import dependencies
  24. * @param {boolean} hasCallback true, if the range wraps an existing callback
  25. */
  26. constructor(range, dependencies, hasCallback) {
  27. super();
  28. this.range = range;
  29. /** @type {HarmonyAcceptImportDependency[]} */
  30. this.dependencies = dependencies;
  31. /** @type {boolean} */
  32. this.hasCallback = hasCallback;
  33. }
  34. get type() {
  35. return "accepted harmony modules";
  36. }
  37. /**
  38. * Serializes this instance into the provided serializer context.
  39. * @param {ObjectSerializerContext} context context
  40. */
  41. serialize(context) {
  42. context.write(this.range).write(this.dependencies).write(this.hasCallback);
  43. super.serialize(context);
  44. }
  45. /**
  46. * Restores this instance from the provided deserializer context.
  47. * @param {ObjectDeserializerContext} context context
  48. */
  49. deserialize(context) {
  50. this.range = context.read();
  51. const c1 = context.rest;
  52. this.dependencies = c1.read();
  53. const c2 = c1.rest;
  54. this.hasCallback = c2.read();
  55. super.deserialize(c2.rest);
  56. }
  57. }
  58. makeSerializable(
  59. HarmonyAcceptDependency,
  60. "webpack/lib/dependencies/HarmonyAcceptDependency"
  61. );
  62. HarmonyAcceptDependency.Template = class HarmonyAcceptDependencyTemplate extends (
  63. NullDependency.Template
  64. ) {
  65. /**
  66. * Applies the plugin by registering its hooks on the compiler.
  67. * @param {Dependency} dependency the dependency for which the template should be applied
  68. * @param {ReplaceSource} source the current replace source which can be modified
  69. * @param {DependencyTemplateContext} templateContext the context object
  70. * @returns {void}
  71. */
  72. apply(dependency, source, templateContext) {
  73. const dep = /** @type {HarmonyAcceptDependency} */ (dependency);
  74. const {
  75. module,
  76. runtime,
  77. runtimeRequirements,
  78. runtimeTemplate,
  79. moduleGraph,
  80. chunkGraph
  81. } = templateContext;
  82. /**
  83. * Checks whether this harmony accept dependency is related harmony import dependency.
  84. * @param {Dependency} a the first dependency
  85. * @param {Dependency} b the second dependency
  86. * @returns {boolean} true if the dependencies are related
  87. */
  88. const isRelatedHarmonyImportDependency = (a, b) => {
  89. if (a === b || !(b instanceof HarmonyImportDependency)) return false;
  90. // Compare modules by reference: an unresolved import (ignored/failed, or a
  91. // deferred lazy-barrel re-export) has no module, and a module not in any
  92. // chunk has a null id — so comparing ids would crash or miss real matches.
  93. const moduleA = moduleGraph.getModule(a);
  94. return moduleA !== null && moduleA === moduleGraph.getModule(b);
  95. };
  96. /**
  97. * HarmonyAcceptImportDependency lacks a lot of information, such as the defer property.
  98. * One HarmonyAcceptImportDependency may need to generate multiple ImportStatements.
  99. * Therefore, we find its original HarmonyImportDependency for code generation.
  100. * @param {HarmonyAcceptImportDependency} dependency the dependency to get harmony import dependencies for
  101. * @returns {HarmonyImportDependency[]} array of related harmony import dependencies
  102. */
  103. const getHarmonyImportDependencies = (dependency) => {
  104. /** @type {HarmonyImportDependency[]} */
  105. const result = [];
  106. /** @type {HarmonyImportDependency | null} */
  107. let deferDependency = null;
  108. /** @type {HarmonyImportDependency | null} */
  109. let noDeferredDependency = null;
  110. for (const d of module.dependencies) {
  111. if (deferDependency && noDeferredDependency) break;
  112. if (isRelatedHarmonyImportDependency(dependency, d)) {
  113. if (
  114. ImportPhaseUtils.isDefer(
  115. /** @type {HarmonyImportDependency} */ (d).phase
  116. )
  117. ) {
  118. deferDependency = /** @type {HarmonyImportDependency} */ (d);
  119. } else {
  120. noDeferredDependency = /** @type {HarmonyImportDependency} */ (d);
  121. }
  122. }
  123. }
  124. if (deferDependency) result.push(deferDependency);
  125. if (noDeferredDependency) result.push(noDeferredDependency);
  126. if (result.length === 0) {
  127. // fallback to the original dependency
  128. result.push(dependency);
  129. }
  130. return result;
  131. };
  132. /** @type {HarmonyImportDependency[]} */
  133. const syncDeps = [];
  134. /** @type {HarmonyAcceptImportDependency[]} */
  135. const asyncDeps = [];
  136. for (const dependency of dep.dependencies) {
  137. const connection = moduleGraph.getConnection(dependency);
  138. if (connection && moduleGraph.isAsync(connection.module)) {
  139. asyncDeps.push(dependency);
  140. } else {
  141. syncDeps.push(...getHarmonyImportDependencies(dependency));
  142. }
  143. }
  144. let content = syncDeps
  145. .map((dependency) => {
  146. const referencedModule = moduleGraph.getModule(dependency);
  147. return {
  148. dependency,
  149. runtimeCondition: referencedModule
  150. ? HarmonyImportDependency.Template.getImportEmittedRuntime(
  151. module,
  152. referencedModule
  153. )
  154. : false
  155. };
  156. })
  157. .filter(({ runtimeCondition }) => runtimeCondition !== false)
  158. .map(({ dependency, runtimeCondition }) => {
  159. const condition = runtimeTemplate.runtimeConditionExpression({
  160. chunkGraph,
  161. runtime,
  162. runtimeCondition,
  163. runtimeRequirements
  164. });
  165. const s = dependency.getImportStatement(true, templateContext);
  166. const code = s[0] + s[1];
  167. if (condition !== "true") {
  168. return `if (${condition}) {\n${Template.indent(code)}\n}\n`;
  169. }
  170. return code;
  171. })
  172. .join("");
  173. const promises = new Map(
  174. asyncDeps.map((dependency) => [
  175. dependency.getImportVar(moduleGraph),
  176. dependency.getModuleExports(templateContext)
  177. ])
  178. );
  179. let optAsync = "";
  180. if (promises.size !== 0) {
  181. optAsync = "async ";
  182. content += new AwaitDependenciesInitFragment(promises).getContent({
  183. ...templateContext,
  184. type: "javascript"
  185. });
  186. }
  187. if (dep.hasCallback) {
  188. if (runtimeTemplate.supportsArrowFunction()) {
  189. source.insert(
  190. dep.range[0],
  191. `${optAsync}__WEBPACK_OUTDATED_DEPENDENCIES__ => { ${content} return (`
  192. );
  193. source.insert(dep.range[1], ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }");
  194. } else {
  195. source.insert(
  196. dep.range[0],
  197. `${optAsync}function(__WEBPACK_OUTDATED_DEPENDENCIES__) { ${content} return (`
  198. );
  199. source.insert(
  200. dep.range[1],
  201. ")(__WEBPACK_OUTDATED_DEPENDENCIES__); }.bind(this)"
  202. );
  203. }
  204. return;
  205. }
  206. const arrow = runtimeTemplate.supportsArrowFunction();
  207. source.insert(
  208. dep.range[1] - 0.5,
  209. `, ${arrow ? `${optAsync}() =>` : `${optAsync}function()`} { ${content} }`
  210. );
  211. }
  212. };
  213. module.exports = HarmonyAcceptDependency;