Module.js 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const util = require("util");
  7. const ChunkGraph = require("./ChunkGraph");
  8. const DependenciesBlock = require("./DependenciesBlock");
  9. const ModuleGraph = require("./ModuleGraph");
  10. const { JS_TYPES } = require("./ModuleSourceTypesConstants");
  11. const RuntimeGlobals = require("./RuntimeGlobals");
  12. const { first } = require("./util/SetHelpers");
  13. const { compareChunksById } = require("./util/comparators");
  14. const makeSerializable = require("./util/makeSerializable");
  15. /** @typedef {import("webpack-sources").Source} Source */
  16. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  17. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  18. /** @typedef {import("./Chunk")} Chunk */
  19. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  20. /** @typedef {import("./ChunkGroup")} ChunkGroup */
  21. /** @typedef {import("./CodeGenerationResults")} CodeGenerationResults */
  22. /** @typedef {import("./Compilation")} Compilation */
  23. /** @typedef {import("./Compilation").AssetInfo} AssetInfo */
  24. /** @typedef {import("./Compilation").UnsafeCacheData} UnsafeCacheData */
  25. /** @typedef {import("./ConcatenationScope")} ConcatenationScope */
  26. /** @typedef {import("./Dependency")} Dependency */
  27. /** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
  28. /** @typedef {import("./DependencyTemplate").CssData} CssData */
  29. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  30. /** @typedef {import("./ExportsInfo").UsageStateType} UsageStateType */
  31. /** @typedef {import("./FileSystemInfo")} FileSystemInfo */
  32. /** @typedef {import("./FileSystemInfo").Snapshot} Snapshot */
  33. /** @typedef {import("./ModuleGraphConnection").ConnectionState} ConnectionState */
  34. /** @typedef {import("./ModuleTypeConstants").ModuleTypes} ModuleTypes */
  35. /** @typedef {import("./NormalModuleFactory")} NormalModuleFactory */
  36. /** @typedef {import("./RequestShortener")} RequestShortener */
  37. /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  38. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  39. /** @typedef {import("./WebpackError")} WebpackError */
  40. /** @typedef {import("./json/JsonData")} JsonData */
  41. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  42. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  43. /** @typedef {import("./util/Hash")} Hash */
  44. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  45. /** @typedef {import("./util/identifier").AssociatedObjectForCache} AssociatedObjectForCache */
  46. /** @typedef {import("./util/runtime").RuntimeSpec} RuntimeSpec */
  47. /** @typedef {"namespace" | "default-only" | "default-with-named" | "dynamic"} ExportsType */
  48. /**
  49. * @template T
  50. * @typedef {import("./util/LazySet")<T>} LazySet<T>
  51. */
  52. /**
  53. * @template T
  54. * @typedef {import("./util/SortableSet")<T>} SortableSet<T>
  55. */
  56. /**
  57. * @typedef {object} SourceContext
  58. * @property {DependencyTemplates} dependencyTemplates the dependency templates
  59. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  60. * @property {ModuleGraph} moduleGraph the module graph
  61. * @property {ChunkGraph} chunkGraph the chunk graph
  62. * @property {RuntimeSpec} runtime the runtimes code should be generated for
  63. * @property {string=} type the type of source that should be generated
  64. */
  65. /** @typedef {ReadonlySet<string>} SourceTypes */
  66. // TODO webpack 6: compilation will be required in CodeGenerationContext
  67. /**
  68. * @typedef {object} CodeGenerationContext
  69. * @property {DependencyTemplates} dependencyTemplates the dependency templates
  70. * @property {RuntimeTemplate} runtimeTemplate the runtime template
  71. * @property {ModuleGraph} moduleGraph the module graph
  72. * @property {ChunkGraph} chunkGraph the chunk graph
  73. * @property {RuntimeSpec} runtime the runtimes code should be generated for
  74. * @property {ConcatenationScope=} concatenationScope when in concatenated module, information about other concatenated modules
  75. * @property {CodeGenerationResults | undefined} codeGenerationResults code generation results of other modules (need to have a codeGenerationDependency to use that)
  76. * @property {Compilation=} compilation the compilation
  77. * @property {SourceTypes=} sourceTypes source types
  78. */
  79. /**
  80. * @typedef {object} ConcatenationBailoutReasonContext
  81. * @property {ModuleGraph} moduleGraph the module graph
  82. * @property {ChunkGraph} chunkGraph the chunk graph
  83. */
  84. /** @typedef {Set<string>} RuntimeRequirements */
  85. /** @typedef {ReadonlySet<string>} ReadOnlyRuntimeRequirements */
  86. /**
  87. * @typedef {object} CodeGenerationResult
  88. * @property {Map<string, Source>} sources the resulting sources for all source types
  89. * @property {Map<string, TODO>=} data the resulting data for all source types
  90. * @property {ReadOnlyRuntimeRequirements | null} runtimeRequirements the runtime requirements
  91. * @property {string=} hash a hash of the code generation result (will be automatically calculated from sources and runtimeRequirements if not provided)
  92. */
  93. /**
  94. * @typedef {object} LibIdentOptions
  95. * @property {string} context absolute context path to which lib ident is relative to
  96. * @property {AssociatedObjectForCache=} associatedObjectForCache object for caching
  97. */
  98. /**
  99. * @typedef {object} KnownBuildMeta
  100. * @property {("default" | "namespace" | "flagged" | "dynamic")=} exportsType
  101. * @property {(false | "redirect" | "redirect-warn")=} defaultObject
  102. * @property {boolean=} strictHarmonyModule
  103. * @property {boolean=} async
  104. * @property {boolean=} sideEffectFree
  105. * @property {boolean=} isCSSModule
  106. * @property {Record<string, string>=} jsIncompatibleExports
  107. * @property {Record<string, string>=} exportsFinalName
  108. * @property {string=} factoryExportsBinding
  109. */
  110. /**
  111. * @typedef {object} KnownBuildInfo
  112. * @property {boolean=} cacheable
  113. * @property {boolean=} parsed
  114. * @property {boolean=} strict
  115. * @property {string=} moduleArgument using in AMD
  116. * @property {string=} exportsArgument using in AMD
  117. * @property {string=} moduleConcatenationBailout using in CommonJs
  118. * @property {boolean=} needCreateRequire using in APIPlugin
  119. * @property {string=} resourceIntegrity using in HttpUriPlugin
  120. * @property {LazySet<string>=} fileDependencies using in NormalModule
  121. * @property {LazySet<string>=} contextDependencies using in NormalModule
  122. * @property {LazySet<string>=} missingDependencies using in NormalModule
  123. * @property {LazySet<string>=} buildDependencies using in NormalModule
  124. * @property {ValueCacheVersions=} valueDependencies using in NormalModule
  125. * @property {Record<string, Source>=} assets using in NormalModule
  126. * @property {Map<string, AssetInfo | undefined>=} assetsInfo using in NormalModule
  127. * @property {string=} hash using in NormalModule
  128. * @property {(Snapshot | null)=} snapshot using in ContextModule
  129. * @property {string=} fullContentHash for assets modules
  130. * @property {string=} filename for assets modules
  131. * @property {boolean=} dataUrl for assets modules
  132. * @property {AssetInfo=} assetInfo for assets modules
  133. * @property {boolean=} javascriptModule for external modules
  134. * @property {boolean=} active for lazy compilation modules
  135. * @property {CssData=} cssData for css modules
  136. * @property {JsonData=} jsonData for json modules
  137. * @property {Set<string>=} topLevelDeclarations top level declaration names
  138. */
  139. /** @typedef {Map<string, string | Set<string>>} ValueCacheVersions */
  140. /**
  141. * @typedef {object} NeedBuildContext
  142. * @property {Compilation} compilation
  143. * @property {FileSystemInfo} fileSystemInfo
  144. * @property {ValueCacheVersions} valueCacheVersions
  145. */
  146. /** @typedef {(err?: WebpackError | null, needBuild?: boolean) => void} NeedBuildCallback */
  147. /** @typedef {(err?: WebpackError) => void} BuildCallback */
  148. /** @typedef {KnownBuildMeta & Record<string, EXPECTED_ANY>} BuildMeta */
  149. /** @typedef {KnownBuildInfo & Record<string, EXPECTED_ANY>} BuildInfo */
  150. /**
  151. * @typedef {object} FactoryMeta
  152. * @property {boolean=} sideEffectFree
  153. */
  154. const EMPTY_RESOLVE_OPTIONS = {};
  155. let debugId = 1000;
  156. const DEFAULT_TYPES_UNKNOWN = new Set(["unknown"]);
  157. const deprecatedNeedRebuild = util.deprecate(
  158. /**
  159. * @param {Module} module the module
  160. * @param {NeedBuildContext} context context info
  161. * @returns {boolean} true, when rebuild is needed
  162. */
  163. (module, context) =>
  164. module.needRebuild(
  165. context.fileSystemInfo.getDeprecatedFileTimestamps(),
  166. context.fileSystemInfo.getDeprecatedContextTimestamps()
  167. ),
  168. "Module.needRebuild is deprecated in favor of Module.needBuild",
  169. "DEP_WEBPACK_MODULE_NEED_REBUILD"
  170. );
  171. /** @typedef {(requestShortener: RequestShortener) => string} OptimizationBailoutFunction */
  172. class Module extends DependenciesBlock {
  173. /**
  174. * @param {ModuleTypes | ""} type the module type, when deserializing the type is not known and is an empty string
  175. * @param {(string | null)=} context an optional context
  176. * @param {(string | null)=} layer an optional layer in which the module is
  177. */
  178. constructor(type, context = null, layer = null) {
  179. super();
  180. /** @type {ModuleTypes} */
  181. this.type = type;
  182. /** @type {string | null} */
  183. this.context = context;
  184. /** @type {string | null} */
  185. this.layer = layer;
  186. /** @type {boolean} */
  187. this.needId = true;
  188. // Unique Id
  189. /** @type {number} */
  190. this.debugId = debugId++;
  191. // Info from Factory
  192. /** @type {ResolveOptions | undefined} */
  193. this.resolveOptions = EMPTY_RESOLVE_OPTIONS;
  194. /** @type {FactoryMeta | undefined} */
  195. this.factoryMeta = undefined;
  196. // TODO refactor this -> options object filled from Factory
  197. // TODO webpack 6: use an enum
  198. /** @type {boolean} */
  199. this.useSourceMap = false;
  200. /** @type {boolean} */
  201. this.useSimpleSourceMap = false;
  202. // Is in hot context, i.e. HotModuleReplacementPlugin.js enabled
  203. // TODO do we need hot here?
  204. /** @type {boolean} */
  205. this.hot = false;
  206. // Info from Build
  207. /** @type {WebpackError[] | undefined} */
  208. this._warnings = undefined;
  209. /** @type {WebpackError[] | undefined} */
  210. this._errors = undefined;
  211. /** @type {BuildMeta | undefined} */
  212. this.buildMeta = undefined;
  213. /** @type {BuildInfo | undefined} */
  214. this.buildInfo = undefined;
  215. /** @type {Dependency[] | undefined} */
  216. this.presentationalDependencies = undefined;
  217. /** @type {Dependency[] | undefined} */
  218. this.codeGenerationDependencies = undefined;
  219. }
  220. // TODO remove in webpack 6
  221. // BACKWARD-COMPAT START
  222. /**
  223. * @returns {ModuleId | null} module id
  224. */
  225. get id() {
  226. return ChunkGraph.getChunkGraphForModule(
  227. this,
  228. "Module.id",
  229. "DEP_WEBPACK_MODULE_ID"
  230. ).getModuleId(this);
  231. }
  232. /**
  233. * @param {ModuleId} value value
  234. */
  235. set id(value) {
  236. if (value === "") {
  237. this.needId = false;
  238. return;
  239. }
  240. ChunkGraph.getChunkGraphForModule(
  241. this,
  242. "Module.id",
  243. "DEP_WEBPACK_MODULE_ID"
  244. ).setModuleId(this, value);
  245. }
  246. /**
  247. * @returns {string} the hash of the module
  248. */
  249. get hash() {
  250. return ChunkGraph.getChunkGraphForModule(
  251. this,
  252. "Module.hash",
  253. "DEP_WEBPACK_MODULE_HASH"
  254. ).getModuleHash(this, undefined);
  255. }
  256. /**
  257. * @returns {string} the shortened hash of the module
  258. */
  259. get renderedHash() {
  260. return ChunkGraph.getChunkGraphForModule(
  261. this,
  262. "Module.renderedHash",
  263. "DEP_WEBPACK_MODULE_RENDERED_HASH"
  264. ).getRenderedModuleHash(this, undefined);
  265. }
  266. get profile() {
  267. return ModuleGraph.getModuleGraphForModule(
  268. this,
  269. "Module.profile",
  270. "DEP_WEBPACK_MODULE_PROFILE"
  271. ).getProfile(this);
  272. }
  273. set profile(value) {
  274. ModuleGraph.getModuleGraphForModule(
  275. this,
  276. "Module.profile",
  277. "DEP_WEBPACK_MODULE_PROFILE"
  278. ).setProfile(this, value);
  279. }
  280. /**
  281. * @returns {number | null} the pre order index
  282. */
  283. get index() {
  284. return ModuleGraph.getModuleGraphForModule(
  285. this,
  286. "Module.index",
  287. "DEP_WEBPACK_MODULE_INDEX"
  288. ).getPreOrderIndex(this);
  289. }
  290. /**
  291. * @param {number} value the pre order index
  292. */
  293. set index(value) {
  294. ModuleGraph.getModuleGraphForModule(
  295. this,
  296. "Module.index",
  297. "DEP_WEBPACK_MODULE_INDEX"
  298. ).setPreOrderIndex(this, value);
  299. }
  300. /**
  301. * @returns {number | null} the post order index
  302. */
  303. get index2() {
  304. return ModuleGraph.getModuleGraphForModule(
  305. this,
  306. "Module.index2",
  307. "DEP_WEBPACK_MODULE_INDEX2"
  308. ).getPostOrderIndex(this);
  309. }
  310. /**
  311. * @param {number} value the post order index
  312. */
  313. set index2(value) {
  314. ModuleGraph.getModuleGraphForModule(
  315. this,
  316. "Module.index2",
  317. "DEP_WEBPACK_MODULE_INDEX2"
  318. ).setPostOrderIndex(this, value);
  319. }
  320. /**
  321. * @returns {number | null} the depth
  322. */
  323. get depth() {
  324. return ModuleGraph.getModuleGraphForModule(
  325. this,
  326. "Module.depth",
  327. "DEP_WEBPACK_MODULE_DEPTH"
  328. ).getDepth(this);
  329. }
  330. /**
  331. * @param {number} value the depth
  332. */
  333. set depth(value) {
  334. ModuleGraph.getModuleGraphForModule(
  335. this,
  336. "Module.depth",
  337. "DEP_WEBPACK_MODULE_DEPTH"
  338. ).setDepth(this, value);
  339. }
  340. /**
  341. * @returns {Module | null | undefined} issuer
  342. */
  343. get issuer() {
  344. return ModuleGraph.getModuleGraphForModule(
  345. this,
  346. "Module.issuer",
  347. "DEP_WEBPACK_MODULE_ISSUER"
  348. ).getIssuer(this);
  349. }
  350. /**
  351. * @param {Module | null} value issuer
  352. */
  353. set issuer(value) {
  354. ModuleGraph.getModuleGraphForModule(
  355. this,
  356. "Module.issuer",
  357. "DEP_WEBPACK_MODULE_ISSUER"
  358. ).setIssuer(this, value);
  359. }
  360. get usedExports() {
  361. return ModuleGraph.getModuleGraphForModule(
  362. this,
  363. "Module.usedExports",
  364. "DEP_WEBPACK_MODULE_USED_EXPORTS"
  365. ).getUsedExports(this, undefined);
  366. }
  367. /**
  368. * @deprecated
  369. * @returns {(string | OptimizationBailoutFunction)[]} list
  370. */
  371. get optimizationBailout() {
  372. return ModuleGraph.getModuleGraphForModule(
  373. this,
  374. "Module.optimizationBailout",
  375. "DEP_WEBPACK_MODULE_OPTIMIZATION_BAILOUT"
  376. ).getOptimizationBailout(this);
  377. }
  378. get optional() {
  379. return this.isOptional(
  380. ModuleGraph.getModuleGraphForModule(
  381. this,
  382. "Module.optional",
  383. "DEP_WEBPACK_MODULE_OPTIONAL"
  384. )
  385. );
  386. }
  387. /**
  388. * @param {Chunk} chunk the chunk
  389. * @returns {boolean} true, when the module was added
  390. */
  391. addChunk(chunk) {
  392. const chunkGraph = ChunkGraph.getChunkGraphForModule(
  393. this,
  394. "Module.addChunk",
  395. "DEP_WEBPACK_MODULE_ADD_CHUNK"
  396. );
  397. if (chunkGraph.isModuleInChunk(this, chunk)) return false;
  398. chunkGraph.connectChunkAndModule(chunk, this);
  399. return true;
  400. }
  401. /**
  402. * @param {Chunk} chunk the chunk
  403. * @returns {void}
  404. */
  405. removeChunk(chunk) {
  406. return ChunkGraph.getChunkGraphForModule(
  407. this,
  408. "Module.removeChunk",
  409. "DEP_WEBPACK_MODULE_REMOVE_CHUNK"
  410. ).disconnectChunkAndModule(chunk, this);
  411. }
  412. /**
  413. * @param {Chunk} chunk the chunk
  414. * @returns {boolean} true, when the module is in the chunk
  415. */
  416. isInChunk(chunk) {
  417. return ChunkGraph.getChunkGraphForModule(
  418. this,
  419. "Module.isInChunk",
  420. "DEP_WEBPACK_MODULE_IS_IN_CHUNK"
  421. ).isModuleInChunk(this, chunk);
  422. }
  423. isEntryModule() {
  424. return ChunkGraph.getChunkGraphForModule(
  425. this,
  426. "Module.isEntryModule",
  427. "DEP_WEBPACK_MODULE_IS_ENTRY_MODULE"
  428. ).isEntryModule(this);
  429. }
  430. getChunks() {
  431. return ChunkGraph.getChunkGraphForModule(
  432. this,
  433. "Module.getChunks",
  434. "DEP_WEBPACK_MODULE_GET_CHUNKS"
  435. ).getModuleChunks(this);
  436. }
  437. getNumberOfChunks() {
  438. return ChunkGraph.getChunkGraphForModule(
  439. this,
  440. "Module.getNumberOfChunks",
  441. "DEP_WEBPACK_MODULE_GET_NUMBER_OF_CHUNKS"
  442. ).getNumberOfModuleChunks(this);
  443. }
  444. get chunksIterable() {
  445. return ChunkGraph.getChunkGraphForModule(
  446. this,
  447. "Module.chunksIterable",
  448. "DEP_WEBPACK_MODULE_CHUNKS_ITERABLE"
  449. ).getOrderedModuleChunksIterable(this, compareChunksById);
  450. }
  451. /**
  452. * @param {string} exportName a name of an export
  453. * @returns {boolean | null} true, if the export is provided why the module.
  454. * null, if it's unknown.
  455. * false, if it's not provided.
  456. */
  457. isProvided(exportName) {
  458. return ModuleGraph.getModuleGraphForModule(
  459. this,
  460. "Module.usedExports",
  461. "DEP_WEBPACK_MODULE_USED_EXPORTS"
  462. ).isExportProvided(this, exportName);
  463. }
  464. // BACKWARD-COMPAT END
  465. /**
  466. * @returns {string} name of the exports argument
  467. */
  468. get exportsArgument() {
  469. return (this.buildInfo && this.buildInfo.exportsArgument) || "exports";
  470. }
  471. /**
  472. * @returns {string} name of the module argument
  473. */
  474. get moduleArgument() {
  475. return (this.buildInfo && this.buildInfo.moduleArgument) || "module";
  476. }
  477. /**
  478. * @param {ModuleGraph} moduleGraph the module graph
  479. * @param {boolean | undefined} strict the importing module is strict
  480. * @returns {ExportsType} export type
  481. * "namespace": Exports is already a namespace object. namespace = exports.
  482. * "dynamic": Check at runtime if __esModule is set. When set: namespace = { ...exports, default: exports }. When not set: namespace = { default: exports }.
  483. * "default-only": Provide a namespace object with only default export. namespace = { default: exports }
  484. * "default-with-named": Provide a namespace object with named and default export. namespace = { ...exports, default: exports }
  485. */
  486. getExportsType(moduleGraph, strict) {
  487. switch (this.buildMeta && this.buildMeta.exportsType) {
  488. case "flagged":
  489. return strict ? "default-with-named" : "namespace";
  490. case "namespace":
  491. return "namespace";
  492. case "default":
  493. switch (/** @type {BuildMeta} */ (this.buildMeta).defaultObject) {
  494. case "redirect":
  495. return "default-with-named";
  496. case "redirect-warn":
  497. return strict ? "default-only" : "default-with-named";
  498. default:
  499. return "default-only";
  500. }
  501. case "dynamic": {
  502. if (strict) return "default-with-named";
  503. // Try to figure out value of __esModule by following reexports
  504. const handleDefault = () => {
  505. switch (/** @type {BuildMeta} */ (this.buildMeta).defaultObject) {
  506. case "redirect":
  507. case "redirect-warn":
  508. return "default-with-named";
  509. default:
  510. return "default-only";
  511. }
  512. };
  513. const exportInfo = moduleGraph.getReadOnlyExportInfo(
  514. this,
  515. "__esModule"
  516. );
  517. if (exportInfo.provided === false) {
  518. return handleDefault();
  519. }
  520. const target = exportInfo.getTarget(moduleGraph);
  521. if (
  522. !target ||
  523. !target.export ||
  524. target.export.length !== 1 ||
  525. target.export[0] !== "__esModule"
  526. ) {
  527. return "dynamic";
  528. }
  529. switch (
  530. target.module.buildMeta &&
  531. target.module.buildMeta.exportsType
  532. ) {
  533. case "flagged":
  534. case "namespace":
  535. return "namespace";
  536. case "default":
  537. return handleDefault();
  538. default:
  539. return "dynamic";
  540. }
  541. }
  542. default:
  543. return strict ? "default-with-named" : "dynamic";
  544. }
  545. }
  546. /**
  547. * @param {Dependency} presentationalDependency dependency being tied to module.
  548. * This is a Dependency without edge in the module graph. It's only for presentation.
  549. * @returns {void}
  550. */
  551. addPresentationalDependency(presentationalDependency) {
  552. if (this.presentationalDependencies === undefined) {
  553. this.presentationalDependencies = [];
  554. }
  555. this.presentationalDependencies.push(presentationalDependency);
  556. }
  557. /**
  558. * @param {Dependency} codeGenerationDependency dependency being tied to module.
  559. * This is a Dependency where the code generation result of the referenced module is needed during code generation.
  560. * The Dependency should also be added to normal dependencies via addDependency.
  561. * @returns {void}
  562. */
  563. addCodeGenerationDependency(codeGenerationDependency) {
  564. if (this.codeGenerationDependencies === undefined) {
  565. this.codeGenerationDependencies = [];
  566. }
  567. this.codeGenerationDependencies.push(codeGenerationDependency);
  568. }
  569. /**
  570. * Removes all dependencies and blocks
  571. * @returns {void}
  572. */
  573. clearDependenciesAndBlocks() {
  574. if (this.presentationalDependencies !== undefined) {
  575. this.presentationalDependencies.length = 0;
  576. }
  577. if (this.codeGenerationDependencies !== undefined) {
  578. this.codeGenerationDependencies.length = 0;
  579. }
  580. super.clearDependenciesAndBlocks();
  581. }
  582. /**
  583. * @param {WebpackError} warning the warning
  584. * @returns {void}
  585. */
  586. addWarning(warning) {
  587. if (this._warnings === undefined) {
  588. this._warnings = [];
  589. }
  590. this._warnings.push(warning);
  591. }
  592. /**
  593. * @returns {Iterable<WebpackError> | undefined} list of warnings if any
  594. */
  595. getWarnings() {
  596. return this._warnings;
  597. }
  598. /**
  599. * @returns {number} number of warnings
  600. */
  601. getNumberOfWarnings() {
  602. return this._warnings !== undefined ? this._warnings.length : 0;
  603. }
  604. /**
  605. * @param {WebpackError} error the error
  606. * @returns {void}
  607. */
  608. addError(error) {
  609. if (this._errors === undefined) {
  610. this._errors = [];
  611. }
  612. this._errors.push(error);
  613. }
  614. /**
  615. * @returns {Iterable<WebpackError> | undefined} list of errors if any
  616. */
  617. getErrors() {
  618. return this._errors;
  619. }
  620. /**
  621. * @returns {number} number of errors
  622. */
  623. getNumberOfErrors() {
  624. return this._errors !== undefined ? this._errors.length : 0;
  625. }
  626. /**
  627. * removes all warnings and errors
  628. * @returns {void}
  629. */
  630. clearWarningsAndErrors() {
  631. if (this._warnings !== undefined) {
  632. this._warnings.length = 0;
  633. }
  634. if (this._errors !== undefined) {
  635. this._errors.length = 0;
  636. }
  637. }
  638. /**
  639. * @param {ModuleGraph} moduleGraph the module graph
  640. * @returns {boolean} true, if the module is optional
  641. */
  642. isOptional(moduleGraph) {
  643. let hasConnections = false;
  644. for (const r of moduleGraph.getIncomingConnections(this)) {
  645. if (
  646. !r.dependency ||
  647. !r.dependency.optional ||
  648. !r.isTargetActive(undefined)
  649. ) {
  650. return false;
  651. }
  652. hasConnections = true;
  653. }
  654. return hasConnections;
  655. }
  656. /**
  657. * @param {ChunkGraph} chunkGraph the chunk graph
  658. * @param {Chunk} chunk a chunk
  659. * @param {Chunk=} ignoreChunk chunk to be ignored
  660. * @returns {boolean} true, if the module is accessible from "chunk" when ignoring "ignoreChunk"
  661. */
  662. isAccessibleInChunk(chunkGraph, chunk, ignoreChunk) {
  663. // Check if module is accessible in ALL chunk groups
  664. for (const chunkGroup of chunk.groupsIterable) {
  665. if (!this.isAccessibleInChunkGroup(chunkGraph, chunkGroup)) return false;
  666. }
  667. return true;
  668. }
  669. /**
  670. * @param {ChunkGraph} chunkGraph the chunk graph
  671. * @param {ChunkGroup} chunkGroup a chunk group
  672. * @param {Chunk=} ignoreChunk chunk to be ignored
  673. * @returns {boolean} true, if the module is accessible from "chunkGroup" when ignoring "ignoreChunk"
  674. */
  675. isAccessibleInChunkGroup(chunkGraph, chunkGroup, ignoreChunk) {
  676. const queue = new Set([chunkGroup]);
  677. // Check if module is accessible from all items of the queue
  678. queueFor: for (const cg of queue) {
  679. // 1. If module is in one of the chunks of the group we can continue checking the next items
  680. // because it's accessible.
  681. for (const chunk of cg.chunks) {
  682. if (chunk !== ignoreChunk && chunkGraph.isModuleInChunk(this, chunk)) {
  683. continue queueFor;
  684. }
  685. }
  686. // 2. If the chunk group is initial, we can break here because it's not accessible.
  687. if (chunkGroup.isInitial()) return false;
  688. // 3. Enqueue all parents because it must be accessible from ALL parents
  689. for (const parent of chunkGroup.parentsIterable) queue.add(parent);
  690. }
  691. // When we processed through the whole list and we didn't bailout, the module is accessible
  692. return true;
  693. }
  694. /**
  695. * @param {Chunk} chunk a chunk
  696. * @param {ModuleGraph} moduleGraph the module graph
  697. * @param {ChunkGraph} chunkGraph the chunk graph
  698. * @returns {boolean} true, if the module has any reason why "chunk" should be included
  699. */
  700. hasReasonForChunk(chunk, moduleGraph, chunkGraph) {
  701. // check for each reason if we need the chunk
  702. for (const [
  703. fromModule,
  704. connections
  705. ] of moduleGraph.getIncomingConnectionsByOriginModule(this)) {
  706. if (!connections.some((c) => c.isTargetActive(chunk.runtime))) continue;
  707. for (const originChunk of chunkGraph.getModuleChunksIterable(
  708. /** @type {Module} */ (fromModule)
  709. )) {
  710. // return true if module this is not reachable from originChunk when ignoring chunk
  711. if (!this.isAccessibleInChunk(chunkGraph, originChunk, chunk)) {
  712. return true;
  713. }
  714. }
  715. }
  716. return false;
  717. }
  718. /**
  719. * @param {ModuleGraph} moduleGraph the module graph
  720. * @param {RuntimeSpec} runtime the runtime
  721. * @returns {boolean} true if at least one other module depends on this module
  722. */
  723. hasReasons(moduleGraph, runtime) {
  724. for (const c of moduleGraph.getIncomingConnections(this)) {
  725. if (c.isTargetActive(runtime)) return true;
  726. }
  727. return false;
  728. }
  729. /**
  730. * @returns {string} for debugging
  731. */
  732. toString() {
  733. return `Module[${this.debugId}: ${this.identifier()}]`;
  734. }
  735. /**
  736. * @param {NeedBuildContext} context context info
  737. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  738. * @returns {void}
  739. */
  740. needBuild(context, callback) {
  741. callback(
  742. null,
  743. !this.buildMeta ||
  744. this.needRebuild === Module.prototype.needRebuild ||
  745. deprecatedNeedRebuild(this, context)
  746. );
  747. }
  748. /**
  749. * @deprecated Use needBuild instead
  750. * @param {Map<string, number|null>} fileTimestamps timestamps of files
  751. * @param {Map<string, number|null>} contextTimestamps timestamps of directories
  752. * @returns {boolean} true, if the module needs a rebuild
  753. */
  754. needRebuild(fileTimestamps, contextTimestamps) {
  755. return true;
  756. }
  757. /**
  758. * @param {Hash} hash the hash used to track dependencies
  759. * @param {UpdateHashContext} context context
  760. * @returns {void}
  761. */
  762. updateHash(
  763. hash,
  764. context = {
  765. chunkGraph: ChunkGraph.getChunkGraphForModule(
  766. this,
  767. "Module.updateHash",
  768. "DEP_WEBPACK_MODULE_UPDATE_HASH"
  769. ),
  770. runtime: undefined
  771. }
  772. ) {
  773. const { chunkGraph, runtime } = context;
  774. hash.update(chunkGraph.getModuleGraphHash(this, runtime));
  775. if (this.presentationalDependencies !== undefined) {
  776. for (const dep of this.presentationalDependencies) {
  777. dep.updateHash(hash, context);
  778. }
  779. }
  780. super.updateHash(hash, context);
  781. }
  782. /**
  783. * @returns {void}
  784. */
  785. invalidateBuild() {
  786. // should be overridden to support this feature
  787. }
  788. /* istanbul ignore next */
  789. /**
  790. * @abstract
  791. * @returns {string} a unique identifier of the module
  792. */
  793. identifier() {
  794. const AbstractMethodError = require("./AbstractMethodError");
  795. throw new AbstractMethodError();
  796. }
  797. /* istanbul ignore next */
  798. /**
  799. * @abstract
  800. * @param {RequestShortener} requestShortener the request shortener
  801. * @returns {string} a user readable identifier of the module
  802. */
  803. readableIdentifier(requestShortener) {
  804. const AbstractMethodError = require("./AbstractMethodError");
  805. throw new AbstractMethodError();
  806. }
  807. /* istanbul ignore next */
  808. /**
  809. * @abstract
  810. * @param {WebpackOptions} options webpack options
  811. * @param {Compilation} compilation the compilation
  812. * @param {ResolverWithOptions} resolver the resolver
  813. * @param {InputFileSystem} fs the file system
  814. * @param {BuildCallback} callback callback function
  815. * @returns {void}
  816. */
  817. build(options, compilation, resolver, fs, callback) {
  818. const AbstractMethodError = require("./AbstractMethodError");
  819. throw new AbstractMethodError();
  820. }
  821. /**
  822. * @abstract
  823. * @returns {SourceTypes} types available (do not mutate)
  824. */
  825. getSourceTypes() {
  826. // Better override this method to return the correct types
  827. if (this.source === Module.prototype.source) {
  828. return DEFAULT_TYPES_UNKNOWN;
  829. }
  830. return JS_TYPES;
  831. }
  832. /**
  833. * @abstract
  834. * @deprecated Use codeGeneration() instead
  835. * @param {DependencyTemplates} dependencyTemplates the dependency templates
  836. * @param {RuntimeTemplate} runtimeTemplate the runtime template
  837. * @param {string=} type the type of source that should be generated
  838. * @returns {Source} generated source
  839. */
  840. source(dependencyTemplates, runtimeTemplate, type = "javascript") {
  841. if (this.codeGeneration === Module.prototype.codeGeneration) {
  842. const AbstractMethodError = require("./AbstractMethodError");
  843. throw new AbstractMethodError();
  844. }
  845. const chunkGraph = ChunkGraph.getChunkGraphForModule(
  846. this,
  847. "Module.source() is deprecated. Use Compilation.codeGenerationResults.getSource(module, runtime, type) instead",
  848. "DEP_WEBPACK_MODULE_SOURCE"
  849. );
  850. /** @type {CodeGenerationContext} */
  851. const codeGenContext = {
  852. dependencyTemplates,
  853. runtimeTemplate,
  854. moduleGraph: chunkGraph.moduleGraph,
  855. chunkGraph,
  856. runtime: undefined,
  857. codeGenerationResults: undefined
  858. };
  859. const sources = this.codeGeneration(codeGenContext).sources;
  860. return /** @type {Source} */ (
  861. type
  862. ? sources.get(type)
  863. : sources.get(/** @type {string} */ (first(this.getSourceTypes())))
  864. );
  865. }
  866. /* istanbul ignore next */
  867. /**
  868. * @abstract
  869. * @param {string=} type the source type for which the size should be estimated
  870. * @returns {number} the estimated size of the module (must be non-zero)
  871. */
  872. size(type) {
  873. const AbstractMethodError = require("./AbstractMethodError");
  874. throw new AbstractMethodError();
  875. }
  876. /**
  877. * @param {LibIdentOptions} options options
  878. * @returns {string | null} an identifier for library inclusion
  879. */
  880. libIdent(options) {
  881. return null;
  882. }
  883. /**
  884. * @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
  885. */
  886. nameForCondition() {
  887. return null;
  888. }
  889. /**
  890. * @param {ConcatenationBailoutReasonContext} context context
  891. * @returns {string | undefined} reason why this module can't be concatenated, undefined when it can be concatenated
  892. */
  893. getConcatenationBailoutReason(context) {
  894. return `Module Concatenation is not implemented for ${this.constructor.name}`;
  895. }
  896. /**
  897. * @param {ModuleGraph} moduleGraph the module graph
  898. * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
  899. */
  900. getSideEffectsConnectionState(moduleGraph) {
  901. return true;
  902. }
  903. /**
  904. * @param {CodeGenerationContext} context context for code generation
  905. * @returns {CodeGenerationResult} result
  906. */
  907. codeGeneration(context) {
  908. // Best override this method
  909. const sources = new Map();
  910. for (const type of this.getSourceTypes()) {
  911. if (type !== "unknown") {
  912. sources.set(
  913. type,
  914. this.source(
  915. context.dependencyTemplates,
  916. context.runtimeTemplate,
  917. type
  918. )
  919. );
  920. }
  921. }
  922. return {
  923. sources,
  924. runtimeRequirements: new Set([
  925. RuntimeGlobals.module,
  926. RuntimeGlobals.exports,
  927. RuntimeGlobals.require
  928. ])
  929. };
  930. }
  931. /**
  932. * @param {Chunk} chunk the chunk which condition should be checked
  933. * @param {Compilation} compilation the compilation
  934. * @returns {boolean} true, if the chunk is ok for the module
  935. */
  936. chunkCondition(chunk, compilation) {
  937. return true;
  938. }
  939. hasChunkCondition() {
  940. return this.chunkCondition !== Module.prototype.chunkCondition;
  941. }
  942. /**
  943. * Assuming this module is in the cache. Update the (cached) module with
  944. * the fresh module from the factory. Usually updates internal references
  945. * and properties.
  946. * @param {Module} module fresh module
  947. * @returns {void}
  948. */
  949. updateCacheModule(module) {
  950. this.type = module.type;
  951. this.layer = module.layer;
  952. this.context = module.context;
  953. this.factoryMeta = module.factoryMeta;
  954. this.resolveOptions = module.resolveOptions;
  955. }
  956. /**
  957. * Module should be unsafe cached. Get data that's needed for that.
  958. * This data will be passed to restoreFromUnsafeCache later.
  959. * @returns {UnsafeCacheData} cached data
  960. */
  961. getUnsafeCacheData() {
  962. return {
  963. factoryMeta: this.factoryMeta,
  964. resolveOptions: this.resolveOptions
  965. };
  966. }
  967. /**
  968. * restore unsafe cache data
  969. * @param {UnsafeCacheData} unsafeCacheData data from getUnsafeCacheData
  970. * @param {NormalModuleFactory} normalModuleFactory the normal module factory handling the unsafe caching
  971. */
  972. _restoreFromUnsafeCache(unsafeCacheData, normalModuleFactory) {
  973. this.factoryMeta = unsafeCacheData.factoryMeta;
  974. this.resolveOptions = unsafeCacheData.resolveOptions;
  975. }
  976. /**
  977. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  978. */
  979. cleanupForCache() {
  980. this.factoryMeta = undefined;
  981. this.resolveOptions = undefined;
  982. }
  983. /**
  984. * @returns {Source | null} the original source for the module before webpack transformation
  985. */
  986. originalSource() {
  987. return null;
  988. }
  989. /**
  990. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  991. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  992. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  993. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  994. */
  995. addCacheDependencies(
  996. fileDependencies,
  997. contextDependencies,
  998. missingDependencies,
  999. buildDependencies
  1000. ) {}
  1001. /**
  1002. * @param {ObjectSerializerContext} context context
  1003. */
  1004. serialize(context) {
  1005. const { write } = context;
  1006. write(this.type);
  1007. write(this.layer);
  1008. write(this.context);
  1009. write(this.resolveOptions);
  1010. write(this.factoryMeta);
  1011. write(this.useSourceMap);
  1012. write(this.useSimpleSourceMap);
  1013. write(this.hot);
  1014. write(
  1015. this._warnings !== undefined && this._warnings.length === 0
  1016. ? undefined
  1017. : this._warnings
  1018. );
  1019. write(
  1020. this._errors !== undefined && this._errors.length === 0
  1021. ? undefined
  1022. : this._errors
  1023. );
  1024. write(this.buildMeta);
  1025. write(this.buildInfo);
  1026. write(this.presentationalDependencies);
  1027. write(this.codeGenerationDependencies);
  1028. super.serialize(context);
  1029. }
  1030. /**
  1031. * @param {ObjectDeserializerContext} context context
  1032. */
  1033. deserialize(context) {
  1034. const { read } = context;
  1035. this.type = read();
  1036. this.layer = read();
  1037. this.context = read();
  1038. this.resolveOptions = read();
  1039. this.factoryMeta = read();
  1040. this.useSourceMap = read();
  1041. this.useSimpleSourceMap = read();
  1042. this.hot = read();
  1043. this._warnings = read();
  1044. this._errors = read();
  1045. this.buildMeta = read();
  1046. this.buildInfo = read();
  1047. this.presentationalDependencies = read();
  1048. this.codeGenerationDependencies = read();
  1049. super.deserialize(context);
  1050. }
  1051. }
  1052. makeSerializable(Module, "webpack/lib/Module");
  1053. // TODO remove in webpack 6
  1054. Object.defineProperty(Module.prototype, "hasEqualsChunks", {
  1055. /**
  1056. * @deprecated
  1057. * @returns {EXPECTED_ANY} throw an error
  1058. */
  1059. get() {
  1060. throw new Error(
  1061. "Module.hasEqualsChunks was renamed (use hasEqualChunks instead)"
  1062. );
  1063. }
  1064. });
  1065. // TODO remove in webpack 6
  1066. Object.defineProperty(Module.prototype, "isUsed", {
  1067. /**
  1068. * @deprecated
  1069. * @returns {EXPECTED_ANY} throw an error
  1070. */
  1071. get() {
  1072. throw new Error(
  1073. "Module.isUsed was renamed (use getUsedName, isExportUsed or isModuleUsed instead)"
  1074. );
  1075. }
  1076. });
  1077. // TODO remove in webpack 6
  1078. Object.defineProperty(Module.prototype, "errors", {
  1079. /**
  1080. * @deprecated
  1081. * @returns {WebpackError[]} errors
  1082. */
  1083. get: util.deprecate(
  1084. /**
  1085. * @this {Module}
  1086. * @returns {WebpackError[]} errors
  1087. */
  1088. function errors() {
  1089. if (this._errors === undefined) {
  1090. this._errors = [];
  1091. }
  1092. return this._errors;
  1093. },
  1094. "Module.errors was removed (use getErrors instead)",
  1095. "DEP_WEBPACK_MODULE_ERRORS"
  1096. )
  1097. });
  1098. // TODO remove in webpack 6
  1099. Object.defineProperty(Module.prototype, "warnings", {
  1100. /**
  1101. * @deprecated
  1102. * @returns {WebpackError[]} warnings
  1103. */
  1104. get: util.deprecate(
  1105. /**
  1106. * @this {Module}
  1107. * @returns {WebpackError[]} warnings
  1108. */
  1109. function warnings() {
  1110. if (this._warnings === undefined) {
  1111. this._warnings = [];
  1112. }
  1113. return this._warnings;
  1114. },
  1115. "Module.warnings was removed (use getWarnings instead)",
  1116. "DEP_WEBPACK_MODULE_WARNINGS"
  1117. )
  1118. });
  1119. // TODO remove in webpack 6
  1120. Object.defineProperty(Module.prototype, "used", {
  1121. /**
  1122. * @deprecated
  1123. * @returns {EXPECTED_ANY} throw an error
  1124. */
  1125. get() {
  1126. throw new Error(
  1127. "Module.used was refactored (use ModuleGraph.getUsedExports instead)"
  1128. );
  1129. },
  1130. /**
  1131. * @param {EXPECTED_ANY} value value
  1132. */
  1133. set(value) {
  1134. throw new Error(
  1135. "Module.used was refactored (use ModuleGraph.setUsedExports instead)"
  1136. );
  1137. }
  1138. });
  1139. module.exports = Module;