HarmonyImportDependency.js 11 KB

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