HarmonyImportDependency.js 11 KB

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