HarmonyImportDependency.js 12 KB

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