ImportDependency.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const Dependency = require("../Dependency");
  7. const Template = require("../Template");
  8. const makeSerializable = require("../util/makeSerializable");
  9. const HarmonyImportGuard = require("./HarmonyImportGuard");
  10. const { ImportPhaseUtils } = require("./ImportPhase");
  11. const ModuleDependency = require("./ModuleDependency");
  12. /** @import { ReplaceSource } from "webpack-sources" */
  13. /** @import AsyncDependenciesBlock from "../AsyncDependenciesBlock" */
  14. /**
  15. * @import {
  16. * GetConditionFn,
  17. * RawReferencedExports,
  18. * ReferencedExports
  19. * } from "../Dependency"
  20. */
  21. /** @import { DependencyTemplateContext } from "../DependencyTemplate" */
  22. /** @import Module, { BuildMeta } from "../Module" */
  23. /** @import ModuleGraph from "../ModuleGraph" */
  24. /** @import { ImportAttributes, Range } from "../javascript/JavascriptParser" */
  25. /**
  26. * @import {
  27. * ObjectDeserializerContext,
  28. * ObjectSerializerContext
  29. * } from "../serialization/ObjectMiddleware"
  30. */
  31. /** @import { RuntimeSpec } from "../util/runtime" */
  32. /** @import { DependencyGuard } from "./HarmonyImportGuard" */
  33. /** @import { ImportPhaseType } from "./ImportPhase" */
  34. class ImportDependency extends ModuleDependency {
  35. /**
  36. * Creates an instance of ImportDependency.
  37. * @param {string} request the request
  38. * @param {Range} range expression range
  39. * @param {RawReferencedExports | null} referencedExports list of referenced exports
  40. * @param {ImportPhaseType} phase import phase
  41. * @param {ImportAttributes=} attributes import attributes
  42. */
  43. constructor(request, range, referencedExports, phase, attributes) {
  44. super(request);
  45. this.range = range;
  46. /** @type {RawReferencedExports | null} */
  47. this.referencedExports = referencedExports;
  48. /** @type {ImportPhaseType} */
  49. this.phase = phase;
  50. /** @type {ImportAttributes | undefined} */
  51. this.attributes = attributes;
  52. /** @type {DependencyGuard[] | undefined} */
  53. this.branchGuards = undefined;
  54. // Range of the `import(specifier, options)` second argument, set only when
  55. // it is not a statically extractable attributes object and must therefore
  56. // be evaluated and validated at runtime.
  57. /** @type {Range | undefined} */
  58. this.optionsRange = undefined;
  59. }
  60. get type() {
  61. return "import()";
  62. }
  63. get category() {
  64. return "esm";
  65. }
  66. /**
  67. * Returns function to determine if the connection is active.
  68. * @param {ModuleGraph} moduleGraph module graph
  69. * @returns {null | false | GetConditionFn} function to determine if the connection is active
  70. */
  71. getCondition(moduleGraph) {
  72. const guards = this.branchGuards;
  73. if (guards === undefined) return null;
  74. return (connection, runtime) =>
  75. !HarmonyImportGuard.isDeadByGuards(guards, moduleGraph, runtime);
  76. }
  77. /**
  78. * Returns an identifier to merge equal requests.
  79. * @returns {string | null} an identifier to merge equal requests
  80. */
  81. getResourceIdentifier() {
  82. let str = super.getResourceIdentifier();
  83. // We specifically use this check to avoid writing the default (`evaluation` or `0`) value and save memory
  84. if (this.phase) {
  85. str += `|phase${ImportPhaseUtils.stringify(this.phase)}`;
  86. }
  87. if (this.attributes) {
  88. str += `|attributes${JSON.stringify(this.attributes)}`;
  89. }
  90. return str;
  91. }
  92. /**
  93. * Returns list of exports referenced by this dependency
  94. * @param {ModuleGraph} moduleGraph module graph
  95. * @param {RuntimeSpec} runtime the runtime for which the module is analysed
  96. * @returns {ReferencedExports} referenced exports
  97. */
  98. getReferencedExports(moduleGraph, runtime) {
  99. if (!this.referencedExports) return Dependency.EXPORTS_OBJECT_REFERENCED;
  100. /** @type {ReferencedExports} */
  101. const refs = [];
  102. for (const referencedExport of this.referencedExports) {
  103. if (referencedExport[0] === "default") {
  104. const selfModule =
  105. /** @type {Module} */
  106. (moduleGraph.getParentModule(this));
  107. const importedModule =
  108. /** @type {Module} */
  109. (moduleGraph.getModule(this));
  110. const exportsType = importedModule.getExportsType(
  111. moduleGraph,
  112. /** @type {BuildMeta} */
  113. (selfModule.buildMeta).strictHarmonyModule
  114. );
  115. if (
  116. exportsType === "default-only" ||
  117. exportsType === "default-with-named"
  118. ) {
  119. return Dependency.EXPORTS_OBJECT_REFERENCED;
  120. }
  121. }
  122. refs.push({
  123. name: referencedExport,
  124. canMangle: false,
  125. canInline: false
  126. });
  127. }
  128. return refs;
  129. }
  130. /**
  131. * Serializes this instance into the provided serializer context.
  132. * @param {ObjectSerializerContext} context context
  133. */
  134. serialize(context) {
  135. context.write(this.range);
  136. context.write(this.referencedExports);
  137. context.write(this.phase);
  138. context.write(this.attributes);
  139. context.write(this.branchGuards);
  140. context.write(this.optionsRange);
  141. super.serialize(context);
  142. }
  143. /**
  144. * Restores this instance from the provided deserializer context.
  145. * @param {ObjectDeserializerContext} context context
  146. */
  147. deserialize(context) {
  148. this.range = context.read();
  149. this.referencedExports = context.read();
  150. this.phase = context.read();
  151. this.attributes = context.read();
  152. this.branchGuards = context.read();
  153. this.optionsRange = context.read();
  154. super.deserialize(context);
  155. }
  156. }
  157. makeSerializable(ImportDependency, "webpack/lib/dependencies/ImportDependency");
  158. ImportDependency.Template = class ImportDependencyTemplate extends (
  159. ModuleDependency.Template
  160. ) {
  161. /**
  162. * Applies the plugin by registering its hooks on the compiler.
  163. * @param {Dependency} dependency the dependency for which the template should be applied
  164. * @param {ReplaceSource} source the current replace source which can be modified
  165. * @param {DependencyTemplateContext} templateContext the context object
  166. * @returns {void}
  167. */
  168. apply(
  169. dependency,
  170. source,
  171. {
  172. runtimeTemplate,
  173. module,
  174. moduleGraph,
  175. chunkGraph,
  176. runtimeRequirements,
  177. runtime
  178. }
  179. ) {
  180. const dep = /** @type {ImportDependency} */ (dependency);
  181. const connection = moduleGraph.getConnection(dep);
  182. // Dead branch: module is excluded and has no id; code is never executed.
  183. if (connection && !connection.isTargetActive(runtime)) {
  184. source.replace(
  185. dep.range[0],
  186. dep.range[1] - 1,
  187. "Promise.resolve(/* dead branch */)"
  188. );
  189. return;
  190. }
  191. const block = /** @type {AsyncDependenciesBlock} */ (
  192. moduleGraph.getParentBlock(dep)
  193. );
  194. let content = runtimeTemplate.moduleNamespacePromise({
  195. chunkGraph,
  196. block,
  197. module: /** @type {Module} */ (moduleGraph.getModule(dep)),
  198. request: dep.request,
  199. strict: /** @type {BuildMeta} */ (module.buildMeta).strictHarmonyModule,
  200. dependency: dep,
  201. message: "import()",
  202. runtimeRequirements,
  203. originModule: module
  204. });
  205. // For source phase imports, unwrap the default export
  206. // import.source() should return the source directly, not a namespace
  207. if (ImportPhaseUtils.isSource(dep.phase)) {
  208. content = `${content}.then(${runtimeTemplate.returningFunction(
  209. 'm["default"]',
  210. "m"
  211. )})`;
  212. }
  213. // A non-static second argument must still be evaluated (for its side
  214. // effects and evaluation order) and validated per spec. Keep it in place
  215. // and wrap it in an inline validator that mirrors the runtime checks of
  216. // the spec's `import(specifier, options)` evaluation.
  217. if (dep.optionsRange) {
  218. const validator = runtimeTemplate.basicFunction("o", [
  219. "try {",
  220. Template.indent([
  221. "if (o !== undefined) {",
  222. Template.indent([
  223. 'if ((typeof o !== "object" && typeof o !== "function") || o === null) throw new TypeError("The second argument to import() must be an object");',
  224. 'var a = o["with"];',
  225. "if (a !== undefined) {",
  226. Template.indent([
  227. 'if ((typeof a !== "object" && typeof a !== "function") || a === null) throw new TypeError("The \'with\' option must be an object");',
  228. "for (var k = Object.keys(a), i = 0; i < k.length; i++) {",
  229. Template.indent([
  230. 'if (typeof a[k[i]] !== "string") throw new TypeError("Import attribute values must be strings");'
  231. ]),
  232. "}"
  233. ]),
  234. "}"
  235. ]),
  236. "}"
  237. ]),
  238. "} catch (e) { return Promise.reject(e); }",
  239. `return ${content};`
  240. ]);
  241. source.replace(dep.range[0], dep.optionsRange[0] - 1, `(${validator})(`);
  242. source.replace(dep.optionsRange[1], dep.range[1] - 1, ")");
  243. return;
  244. }
  245. source.replace(dep.range[0], dep.range[1] - 1, content);
  246. }
  247. };
  248. module.exports = ImportDependency;