Module.js 35 KB

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