HarmonyImportDependency.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const ConditionalInitFragment = require("../ConditionalInitFragment");
  7. const Dependency = require("../Dependency");
  8. const HarmonyLinkingError = require("../HarmonyLinkingError");
  9. const InitFragment = require("../InitFragment");
  10. const Template = require("../Template");
  11. const AwaitDependenciesInitFragment = require("../async-modules/AwaitDependenciesInitFragment");
  12. const { filterRuntime, mergeRuntime } = require("../util/runtime");
  13. const ModuleDependency = require("./ModuleDependency");
  14. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  15. /** @typedef {import("webpack-sources").Source} Source */
  16. /** @typedef {import("../ChunkGraph")} ChunkGraph */
  17. /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
  18. /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */
  19. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  20. /** @typedef {import("../ExportsInfo")} ExportsInfo */
  21. /** @typedef {import("../Module")} Module */
  22. /** @typedef {import("../Module").BuildMeta} BuildMeta */
  23. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  24. /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */
  25. /** @typedef {import("../WebpackError")} WebpackError */
  26. /** @typedef {import("../javascript/JavascriptParser").ImportAttributes} ImportAttributes */
  27. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  28. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  29. /** @typedef {import("../util/Hash")} Hash */
  30. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  31. /** @typedef {0 | 1 | 2 | 3 | false} ExportPresenceMode */
  32. const ExportPresenceModes = {
  33. NONE: /** @type {ExportPresenceMode} */ (0),
  34. WARN: /** @type {ExportPresenceMode} */ (1),
  35. AUTO: /** @type {ExportPresenceMode} */ (2),
  36. ERROR: /** @type {ExportPresenceMode} */ (3),
  37. /**
  38. * @param {string | false} str param
  39. * @returns {ExportPresenceMode} result
  40. */
  41. fromUserOption(str) {
  42. switch (str) {
  43. case "error":
  44. return ExportPresenceModes.ERROR;
  45. case "warn":
  46. return ExportPresenceModes.WARN;
  47. case "auto":
  48. return ExportPresenceModes.AUTO;
  49. case false:
  50. return ExportPresenceModes.NONE;
  51. default:
  52. throw new Error(`Invalid export presence value ${str}`);
  53. }
  54. }
  55. };
  56. class HarmonyImportDependency extends ModuleDependency {
  57. /**
  58. * @param {string} request request string
  59. * @param {number} sourceOrder source order
  60. * @param {ImportAttributes=} attributes import attributes
  61. */
  62. constructor(request, sourceOrder, attributes) {
  63. super(request);
  64. this.sourceOrder = sourceOrder;
  65. this.assertions = attributes;
  66. }
  67. get category() {
  68. return "esm";
  69. }
  70. /**
  71. * Returns list of exports referenced by this dependency
  72. * @param {ModuleGraph} moduleGraph module graph
  73. * @param {RuntimeSpec} runtime the runtime for which the module is analysed
  74. * @returns {(string[] | ReferencedExport)[]} referenced exports
  75. */
  76. getReferencedExports(moduleGraph, runtime) {
  77. return Dependency.NO_EXPORTS_REFERENCED;
  78. }
  79. /**
  80. * @param {ModuleGraph} moduleGraph the module graph
  81. * @returns {string} name of the variable for the import
  82. */
  83. getImportVar(moduleGraph) {
  84. const module = /** @type {Module} */ (moduleGraph.getParentModule(this));
  85. const meta = moduleGraph.getMeta(module);
  86. const defer = this.defer;
  87. const metaKey = defer ? "deferredImportVarMap" : "importVarMap";
  88. let importVarMap = meta[metaKey];
  89. if (!importVarMap) meta[metaKey] = importVarMap = new Map();
  90. let importVar = importVarMap.get(
  91. /** @type {Module} */ (moduleGraph.getModule(this))
  92. );
  93. if (importVar) return importVar;
  94. importVar = `${Template.toIdentifier(
  95. `${this.userRequest}`
  96. )}__WEBPACK_${this.defer ? "DEFERRED_" : ""}IMPORTED_MODULE_${importVarMap.size}__`;
  97. importVarMap.set(
  98. /** @type {Module} */ (moduleGraph.getModule(this)),
  99. importVar
  100. );
  101. return importVar;
  102. }
  103. /**
  104. * @param {boolean} update create new variables or update existing one
  105. * @param {DependencyTemplateContext} templateContext the template context
  106. * @returns {[string, string]} the import statement and the compat statement
  107. */
  108. getImportStatement(
  109. update,
  110. { runtimeTemplate, module, moduleGraph, chunkGraph, runtimeRequirements }
  111. ) {
  112. return runtimeTemplate.importStatement({
  113. update,
  114. module: /** @type {Module} */ (moduleGraph.getModule(this)),
  115. moduleGraph,
  116. chunkGraph,
  117. importVar: this.getImportVar(moduleGraph),
  118. request: this.request,
  119. originModule: module,
  120. runtimeRequirements,
  121. defer: this.defer
  122. });
  123. }
  124. /**
  125. * @param {ModuleGraph} moduleGraph module graph
  126. * @param {string[]} ids imported ids
  127. * @param {string} additionalMessage extra info included in the error message
  128. * @returns {WebpackError[] | undefined} errors
  129. */
  130. getLinkingErrors(moduleGraph, ids, additionalMessage) {
  131. const importedModule = moduleGraph.getModule(this);
  132. // ignore errors for missing or failed modules
  133. if (!importedModule || importedModule.getNumberOfErrors() > 0) {
  134. return;
  135. }
  136. const parentModule =
  137. /** @type {Module} */
  138. (moduleGraph.getParentModule(this));
  139. const exportsType = importedModule.getExportsType(
  140. moduleGraph,
  141. /** @type {BuildMeta} */ (parentModule.buildMeta).strictHarmonyModule
  142. );
  143. if (exportsType === "namespace" || exportsType === "default-with-named") {
  144. if (ids.length === 0) {
  145. return;
  146. }
  147. if (
  148. (exportsType !== "default-with-named" || ids[0] !== "default") &&
  149. moduleGraph.isExportProvided(importedModule, ids) === false
  150. ) {
  151. // We are sure that it's not provided
  152. // Try to provide detailed info in the error message
  153. let pos = 0;
  154. let exportsInfo = moduleGraph.getExportsInfo(importedModule);
  155. while (pos < ids.length && exportsInfo) {
  156. const id = ids[pos++];
  157. const exportInfo = exportsInfo.getReadOnlyExportInfo(id);
  158. if (exportInfo.provided === false) {
  159. // We are sure that it's not provided
  160. const providedExports = exportsInfo.getProvidedExports();
  161. const moreInfo = !Array.isArray(providedExports)
  162. ? " (possible exports unknown)"
  163. : providedExports.length === 0
  164. ? " (module has no exports)"
  165. : ` (possible exports: ${providedExports.join(", ")})`;
  166. return [
  167. new HarmonyLinkingError(
  168. `export ${ids
  169. .slice(0, pos)
  170. .map(id => `'${id}'`)
  171. .join(".")} ${additionalMessage} was not found in '${
  172. this.userRequest
  173. }'${moreInfo}`
  174. )
  175. ];
  176. }
  177. exportsInfo =
  178. /** @type {ExportsInfo} */
  179. (exportInfo.getNestedExportsInfo());
  180. }
  181. // General error message
  182. return [
  183. new HarmonyLinkingError(
  184. `export ${ids
  185. .map(id => `'${id}'`)
  186. .join(".")} ${additionalMessage} was not found in '${
  187. this.userRequest
  188. }'`
  189. )
  190. ];
  191. }
  192. }
  193. switch (exportsType) {
  194. case "default-only":
  195. // It's has only a default export
  196. if (ids.length > 0 && ids[0] !== "default") {
  197. // In strict harmony modules we only support the default export
  198. return [
  199. new HarmonyLinkingError(
  200. `Can't import the named export ${ids
  201. .map(id => `'${id}'`)
  202. .join(
  203. "."
  204. )} ${additionalMessage} from default-exporting module (only default export is available)`
  205. )
  206. ];
  207. }
  208. break;
  209. case "default-with-named":
  210. // It has a default export and named properties redirect
  211. // In some cases we still want to warn here
  212. if (
  213. ids.length > 0 &&
  214. ids[0] !== "default" &&
  215. /** @type {BuildMeta} */
  216. (importedModule.buildMeta).defaultObject === "redirect-warn"
  217. ) {
  218. // For these modules only the default export is supported
  219. return [
  220. new HarmonyLinkingError(
  221. `Should not import the named export ${ids
  222. .map(id => `'${id}'`)
  223. .join(
  224. "."
  225. )} ${additionalMessage} from default-exporting module (only default export is available soon)`
  226. )
  227. ];
  228. }
  229. break;
  230. }
  231. }
  232. /**
  233. * @param {ObjectSerializerContext} context context
  234. */
  235. serialize(context) {
  236. const { write } = context;
  237. write(this.sourceOrder);
  238. write(this.assertions);
  239. super.serialize(context);
  240. }
  241. /**
  242. * @param {ObjectDeserializerContext} context context
  243. */
  244. deserialize(context) {
  245. const { read } = context;
  246. this.sourceOrder = read();
  247. this.assertions = read();
  248. super.deserialize(context);
  249. }
  250. }
  251. module.exports = HarmonyImportDependency;
  252. /** @type {WeakMap<Module, WeakMap<Module, RuntimeSpec | boolean>>} */
  253. const importEmittedMap = new WeakMap();
  254. HarmonyImportDependency.Template = class HarmonyImportDependencyTemplate extends (
  255. ModuleDependency.Template
  256. ) {
  257. /**
  258. * @param {Dependency} dependency the dependency for which the template should be applied
  259. * @param {ReplaceSource} source the current replace source which can be modified
  260. * @param {DependencyTemplateContext} templateContext the context object
  261. * @returns {void}
  262. */
  263. apply(dependency, source, templateContext) {
  264. const dep = /** @type {HarmonyImportDependency} */ (dependency);
  265. const { module, chunkGraph, moduleGraph, runtime } = templateContext;
  266. const connection = moduleGraph.getConnection(dep);
  267. if (connection && !connection.isTargetActive(runtime)) return;
  268. const referencedModule = connection && connection.module;
  269. if (
  270. connection &&
  271. connection.weak &&
  272. referencedModule &&
  273. chunkGraph.getModuleId(referencedModule) === null
  274. ) {
  275. // in weak references, module might not be in any chunk
  276. // but that's ok, we don't need that logic in this case
  277. return;
  278. }
  279. const moduleKey = referencedModule
  280. ? referencedModule.identifier()
  281. : dep.request;
  282. const key = `${dep.defer ? "deferred " : ""}harmony import ${moduleKey}`;
  283. const runtimeCondition = dep.weak
  284. ? false
  285. : connection
  286. ? filterRuntime(runtime, r => connection.isTargetActive(r))
  287. : true;
  288. if (module && referencedModule) {
  289. let emittedModules = importEmittedMap.get(module);
  290. if (emittedModules === undefined) {
  291. emittedModules = new WeakMap();
  292. importEmittedMap.set(module, emittedModules);
  293. }
  294. let mergedRuntimeCondition = runtimeCondition;
  295. const oldRuntimeCondition = emittedModules.get(referencedModule) || false;
  296. if (oldRuntimeCondition !== false && mergedRuntimeCondition !== true) {
  297. if (mergedRuntimeCondition === false || oldRuntimeCondition === true) {
  298. mergedRuntimeCondition = oldRuntimeCondition;
  299. } else {
  300. mergedRuntimeCondition = mergeRuntime(
  301. oldRuntimeCondition,
  302. mergedRuntimeCondition
  303. );
  304. }
  305. }
  306. emittedModules.set(referencedModule, mergedRuntimeCondition);
  307. }
  308. const importStatement = dep.getImportStatement(false, templateContext);
  309. if (
  310. referencedModule &&
  311. templateContext.moduleGraph.isAsync(referencedModule)
  312. ) {
  313. templateContext.initFragments.push(
  314. new ConditionalInitFragment(
  315. importStatement[0],
  316. InitFragment.STAGE_HARMONY_IMPORTS,
  317. dep.sourceOrder,
  318. key,
  319. runtimeCondition
  320. )
  321. );
  322. templateContext.initFragments.push(
  323. new AwaitDependenciesInitFragment(
  324. new Set([dep.getImportVar(templateContext.moduleGraph)])
  325. )
  326. );
  327. templateContext.initFragments.push(
  328. new ConditionalInitFragment(
  329. importStatement[1],
  330. InitFragment.STAGE_ASYNC_HARMONY_IMPORTS,
  331. dep.sourceOrder,
  332. `${key} compat`,
  333. runtimeCondition
  334. )
  335. );
  336. } else {
  337. templateContext.initFragments.push(
  338. new ConditionalInitFragment(
  339. importStatement[0] + importStatement[1],
  340. InitFragment.STAGE_HARMONY_IMPORTS,
  341. dep.sourceOrder,
  342. key,
  343. runtimeCondition
  344. )
  345. );
  346. }
  347. }
  348. /**
  349. * @param {Module} module the module
  350. * @param {Module} referencedModule the referenced module
  351. * @returns {RuntimeSpec | boolean} runtimeCondition in which this import has been emitted
  352. */
  353. static getImportEmittedRuntime(module, referencedModule) {
  354. const emittedModules = importEmittedMap.get(module);
  355. if (emittedModules === undefined) return false;
  356. return emittedModules.get(referencedModule) || false;
  357. }
  358. };
  359. module.exports.ExportPresenceModes = ExportPresenceModes;