Module.js 34 KB

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