CommonJsExportRequireDependency.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 { UsageState } = require("../ExportsInfo");
  8. const Template = require("../Template");
  9. const { equals } = require("../util/ArrayHelpers");
  10. const makeSerializable = require("../util/makeSerializable");
  11. const propertyAccess = require("../util/propertyAccess");
  12. const { handleDependencyBase } = require("./CommonJsDependencyHelpers");
  13. const ModuleDependency = require("./ModuleDependency");
  14. const processExportInfo = require("./processExportInfo");
  15. /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */
  16. /** @typedef {import("../Dependency").ExportsSpec} ExportsSpec */
  17. /** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */
  18. /** @typedef {import("../Dependency").TRANSITIVE} TRANSITIVE */
  19. /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */
  20. /** @typedef {import("../Module")} Module */
  21. /** @typedef {import("../ModuleGraph")} ModuleGraph */
  22. /** @typedef {import("../javascript/JavascriptParser").Range} Range */
  23. /** @typedef {import("../serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  24. /** @typedef {import("../serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  25. /** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */
  26. /** @typedef {import("./CommonJsDependencyHelpers").CommonJSDependencyBaseKeywords} CommonJSDependencyBaseKeywords */
  27. const idsSymbol = Symbol("CommonJsExportRequireDependency.ids");
  28. const EMPTY_OBJECT = {};
  29. class CommonJsExportRequireDependency extends ModuleDependency {
  30. /**
  31. * @param {Range} range range
  32. * @param {Range} valueRange value range
  33. * @param {CommonJSDependencyBaseKeywords} base base
  34. * @param {string[]} names names
  35. * @param {string} request request
  36. * @param {string[]} ids ids
  37. * @param {boolean} resultUsed true, when the result is used
  38. */
  39. constructor(range, valueRange, base, names, request, ids, resultUsed) {
  40. super(request);
  41. this.range = range;
  42. this.valueRange = valueRange;
  43. this.base = base;
  44. this.names = names;
  45. this.ids = ids;
  46. this.resultUsed = resultUsed;
  47. this.asiSafe = undefined;
  48. }
  49. get type() {
  50. return "cjs export require";
  51. }
  52. /**
  53. * @returns {boolean | TRANSITIVE} true, when changes to the referenced module could affect the referencing module; TRANSITIVE, when changes to the referenced module could affect referencing modules of the referencing module
  54. */
  55. couldAffectReferencingModule() {
  56. return Dependency.TRANSITIVE;
  57. }
  58. /**
  59. * @param {ModuleGraph} moduleGraph the module graph
  60. * @returns {string[]} the imported id
  61. */
  62. getIds(moduleGraph) {
  63. return moduleGraph.getMeta(this)[idsSymbol] || this.ids;
  64. }
  65. /**
  66. * @param {ModuleGraph} moduleGraph the module graph
  67. * @param {string[]} ids the imported ids
  68. * @returns {void}
  69. */
  70. setIds(moduleGraph, ids) {
  71. moduleGraph.getMeta(this)[idsSymbol] = ids;
  72. }
  73. /**
  74. * Returns list of exports referenced by this dependency
  75. * @param {ModuleGraph} moduleGraph module graph
  76. * @param {RuntimeSpec} runtime the runtime for which the module is analysed
  77. * @returns {(string[] | ReferencedExport)[]} referenced exports
  78. */
  79. getReferencedExports(moduleGraph, runtime) {
  80. const ids = this.getIds(moduleGraph);
  81. const getFullResult = () => {
  82. if (ids.length === 0) {
  83. return Dependency.EXPORTS_OBJECT_REFERENCED;
  84. } else {
  85. return [
  86. {
  87. name: ids,
  88. canMangle: false
  89. }
  90. ];
  91. }
  92. };
  93. if (this.resultUsed) return getFullResult();
  94. let exportsInfo = moduleGraph.getExportsInfo(
  95. moduleGraph.getParentModule(this)
  96. );
  97. for (const name of this.names) {
  98. const exportInfo = exportsInfo.getReadOnlyExportInfo(name);
  99. const used = exportInfo.getUsed(runtime);
  100. if (used === UsageState.Unused) return Dependency.NO_EXPORTS_REFERENCED;
  101. if (used !== UsageState.OnlyPropertiesUsed) return getFullResult();
  102. exportsInfo = exportInfo.exportsInfo;
  103. if (!exportsInfo) return getFullResult();
  104. }
  105. if (exportsInfo.otherExportsInfo.getUsed(runtime) !== UsageState.Unused) {
  106. return getFullResult();
  107. }
  108. /** @type {string[][]} */
  109. const referencedExports = [];
  110. for (const exportInfo of exportsInfo.orderedExports) {
  111. processExportInfo(
  112. runtime,
  113. referencedExports,
  114. ids.concat(exportInfo.name),
  115. exportInfo,
  116. false
  117. );
  118. }
  119. return referencedExports.map(name => ({
  120. name,
  121. canMangle: false
  122. }));
  123. }
  124. /**
  125. * Returns the exported names
  126. * @param {ModuleGraph} moduleGraph module graph
  127. * @returns {ExportsSpec | undefined} export names
  128. */
  129. getExports(moduleGraph) {
  130. const ids = this.getIds(moduleGraph);
  131. if (this.names.length === 1) {
  132. const name = this.names[0];
  133. const from = moduleGraph.getConnection(this);
  134. if (!from) return;
  135. return {
  136. exports: [
  137. {
  138. name,
  139. from,
  140. export: ids.length === 0 ? null : ids,
  141. // we can't mangle names that are in an empty object
  142. // because one could access the prototype property
  143. // when export isn't set yet
  144. canMangle: !(name in EMPTY_OBJECT) && false
  145. }
  146. ],
  147. dependencies: [from.module]
  148. };
  149. } else if (this.names.length > 0) {
  150. const name = this.names[0];
  151. return {
  152. exports: [
  153. {
  154. name,
  155. // we can't mangle names that are in an empty object
  156. // because one could access the prototype property
  157. // when export isn't set yet
  158. canMangle: !(name in EMPTY_OBJECT) && false
  159. }
  160. ],
  161. dependencies: undefined
  162. };
  163. } else {
  164. const from = moduleGraph.getConnection(this);
  165. if (!from) return;
  166. const reexportInfo = this.getStarReexports(
  167. moduleGraph,
  168. undefined,
  169. from.module
  170. );
  171. if (reexportInfo) {
  172. return {
  173. exports: Array.from(reexportInfo.exports, name => {
  174. return {
  175. name,
  176. from,
  177. export: ids.concat(name),
  178. canMangle: !(name in EMPTY_OBJECT) && false
  179. };
  180. }),
  181. // TODO handle deep reexports
  182. dependencies: [from.module]
  183. };
  184. } else {
  185. return {
  186. exports: true,
  187. from: ids.length === 0 ? from : undefined,
  188. canMangle: false,
  189. dependencies: [from.module]
  190. };
  191. }
  192. }
  193. }
  194. /**
  195. * @param {ModuleGraph} moduleGraph the module graph
  196. * @param {RuntimeSpec} runtime the runtime
  197. * @param {Module} importedModule the imported module (optional)
  198. * @returns {{exports?: Set<string>, checked?: Set<string>}} information
  199. */
  200. getStarReexports(
  201. moduleGraph,
  202. runtime,
  203. importedModule = moduleGraph.getModule(this)
  204. ) {
  205. let importedExportsInfo = moduleGraph.getExportsInfo(importedModule);
  206. const ids = this.getIds(moduleGraph);
  207. if (ids.length > 0)
  208. importedExportsInfo = importedExportsInfo.getNestedExportsInfo(ids);
  209. let exportsInfo = moduleGraph.getExportsInfo(
  210. moduleGraph.getParentModule(this)
  211. );
  212. if (this.names.length > 0)
  213. exportsInfo = exportsInfo.getNestedExportsInfo(this.names);
  214. const noExtraExports =
  215. importedExportsInfo &&
  216. importedExportsInfo.otherExportsInfo.provided === false;
  217. const noExtraImports =
  218. exportsInfo &&
  219. exportsInfo.otherExportsInfo.getUsed(runtime) === UsageState.Unused;
  220. if (!noExtraExports && !noExtraImports) {
  221. return;
  222. }
  223. const isNamespaceImport =
  224. importedModule.getExportsType(moduleGraph, false) === "namespace";
  225. /** @type {Set<string>} */
  226. const exports = new Set();
  227. /** @type {Set<string>} */
  228. const checked = new Set();
  229. if (noExtraImports) {
  230. for (const exportInfo of exportsInfo.orderedExports) {
  231. const name = exportInfo.name;
  232. if (exportInfo.getUsed(runtime) === UsageState.Unused) continue;
  233. if (name === "__esModule" && isNamespaceImport) {
  234. exports.add(name);
  235. } else if (importedExportsInfo) {
  236. const importedExportInfo =
  237. importedExportsInfo.getReadOnlyExportInfo(name);
  238. if (importedExportInfo.provided === false) continue;
  239. exports.add(name);
  240. if (importedExportInfo.provided === true) continue;
  241. checked.add(name);
  242. } else {
  243. exports.add(name);
  244. checked.add(name);
  245. }
  246. }
  247. } else if (noExtraExports) {
  248. for (const importedExportInfo of importedExportsInfo.orderedExports) {
  249. const name = importedExportInfo.name;
  250. if (importedExportInfo.provided === false) continue;
  251. if (exportsInfo) {
  252. const exportInfo = exportsInfo.getReadOnlyExportInfo(name);
  253. if (exportInfo.getUsed(runtime) === UsageState.Unused) continue;
  254. }
  255. exports.add(name);
  256. if (importedExportInfo.provided === true) continue;
  257. checked.add(name);
  258. }
  259. if (isNamespaceImport) {
  260. exports.add("__esModule");
  261. checked.delete("__esModule");
  262. }
  263. }
  264. return { exports, checked };
  265. }
  266. /**
  267. * @param {ObjectSerializerContext} context context
  268. */
  269. serialize(context) {
  270. const { write } = context;
  271. write(this.asiSafe);
  272. write(this.range);
  273. write(this.valueRange);
  274. write(this.base);
  275. write(this.names);
  276. write(this.ids);
  277. write(this.resultUsed);
  278. super.serialize(context);
  279. }
  280. /**
  281. * @param {ObjectDeserializerContext} context context
  282. */
  283. deserialize(context) {
  284. const { read } = context;
  285. this.asiSafe = read();
  286. this.range = read();
  287. this.valueRange = read();
  288. this.base = read();
  289. this.names = read();
  290. this.ids = read();
  291. this.resultUsed = read();
  292. super.deserialize(context);
  293. }
  294. }
  295. makeSerializable(
  296. CommonJsExportRequireDependency,
  297. "webpack/lib/dependencies/CommonJsExportRequireDependency"
  298. );
  299. CommonJsExportRequireDependency.Template = class CommonJsExportRequireDependencyTemplate extends (
  300. ModuleDependency.Template
  301. ) {
  302. /**
  303. * @param {Dependency} dependency the dependency for which the template should be applied
  304. * @param {ReplaceSource} source the current replace source which can be modified
  305. * @param {DependencyTemplateContext} templateContext the context object
  306. * @returns {void}
  307. */
  308. apply(
  309. dependency,
  310. source,
  311. {
  312. module,
  313. runtimeTemplate,
  314. chunkGraph,
  315. moduleGraph,
  316. runtimeRequirements,
  317. runtime
  318. }
  319. ) {
  320. const dep = /** @type {CommonJsExportRequireDependency} */ (dependency);
  321. const used = moduleGraph
  322. .getExportsInfo(module)
  323. .getUsedName(dep.names, runtime);
  324. const [type, base] = handleDependencyBase(
  325. dep.base,
  326. module,
  327. runtimeRequirements
  328. );
  329. const importedModule = moduleGraph.getModule(dep);
  330. let requireExpr = runtimeTemplate.moduleExports({
  331. module: importedModule,
  332. chunkGraph,
  333. request: dep.request,
  334. weak: dep.weak,
  335. runtimeRequirements
  336. });
  337. if (importedModule) {
  338. const ids = dep.getIds(moduleGraph);
  339. const usedImported = moduleGraph
  340. .getExportsInfo(importedModule)
  341. .getUsedName(ids, runtime);
  342. if (usedImported) {
  343. const comment = equals(usedImported, ids)
  344. ? ""
  345. : Template.toNormalComment(propertyAccess(ids)) + " ";
  346. requireExpr += `${comment}${propertyAccess(usedImported)}`;
  347. }
  348. }
  349. switch (type) {
  350. case "expression":
  351. source.replace(
  352. dep.range[0],
  353. dep.range[1] - 1,
  354. used
  355. ? `${base}${propertyAccess(used)} = ${requireExpr}`
  356. : `/* unused reexport */ ${requireExpr}`
  357. );
  358. return;
  359. case "Object.defineProperty":
  360. throw new Error("TODO");
  361. default:
  362. throw new Error("Unexpected type");
  363. }
  364. }
  365. };
  366. module.exports = CommonJsExportRequireDependency;