ContextModule.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const { OriginalSource, RawSource } = require("webpack-sources");
  7. const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
  8. const { makeWebpackError } = require("./HookWebpackError");
  9. const Module = require("./Module");
  10. const { JS_TYPES } = require("./ModuleSourceTypesConstants");
  11. const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
  12. const RuntimeGlobals = require("./RuntimeGlobals");
  13. const Template = require("./Template");
  14. const WebpackError = require("./WebpackError");
  15. const {
  16. compareLocations,
  17. concatComparators,
  18. compareSelect,
  19. keepOriginalOrder,
  20. compareModulesById
  21. } = require("./util/comparators");
  22. const {
  23. contextify,
  24. parseResource,
  25. makePathsRelative
  26. } = require("./util/identifier");
  27. const makeSerializable = require("./util/makeSerializable");
  28. /** @typedef {import("webpack-sources").Source} Source */
  29. /** @typedef {import("../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  30. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  31. /** @typedef {import("./Chunk")} Chunk */
  32. /** @typedef {import("./Chunk").ChunkId} ChunkId */
  33. /** @typedef {import("./ChunkGraph")} ChunkGraph */
  34. /** @typedef {import("./ChunkGraph").ModuleId} ModuleId */
  35. /** @typedef {import("./ChunkGroup").RawChunkGroupOptions} RawChunkGroupOptions */
  36. /** @typedef {import("./Compilation")} Compilation */
  37. /** @typedef {import("./Dependency")} Dependency */
  38. /** @typedef {import("./DependencyTemplates")} DependencyTemplates */
  39. /** @typedef {import("./Generator").SourceTypes} SourceTypes */
  40. /** @typedef {import("./Module").BuildCallback} BuildCallback */
  41. /** @typedef {import("./Module").BuildInfo} BuildInfo */
  42. /** @typedef {import("./Module").BuildMeta} BuildMeta */
  43. /** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
  44. /** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
  45. /** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
  46. /** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
  47. /** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
  48. /** @typedef {import("./ModuleGraph")} ModuleGraph */
  49. /** @typedef {import("./RequestShortener")} RequestShortener */
  50. /** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
  51. /** @typedef {import("./RuntimeTemplate")} RuntimeTemplate */
  52. /** @typedef {import("./dependencies/ContextElementDependency")} ContextElementDependency */
  53. /** @typedef {import("./javascript/JavascriptParser").ImportAttributes} ImportAttributes */
  54. /** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
  55. /** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
  56. /** @template T @typedef {import("./util/LazySet")<T>} LazySet<T> */
  57. /** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
  58. /** @typedef {"sync" | "eager" | "weak" | "async-weak" | "lazy" | "lazy-once"} ContextMode Context mode */
  59. /**
  60. * @typedef {object} ContextOptions
  61. * @property {ContextMode} mode
  62. * @property {boolean} recursive
  63. * @property {RegExp} regExp
  64. * @property {("strict" | boolean)=} namespaceObject
  65. * @property {string=} addon
  66. * @property {(string | null)=} chunkName
  67. * @property {(RegExp | null)=} include
  68. * @property {(RegExp | null)=} exclude
  69. * @property {RawChunkGroupOptions=} groupOptions
  70. * @property {string=} typePrefix
  71. * @property {string=} category
  72. * @property {(string[][] | null)=} referencedExports exports referenced from modules (won't be mangled)
  73. * @property {string=} layer
  74. * @property {ImportAttributes=} attributes
  75. */
  76. /**
  77. * @typedef {object} ContextModuleOptionsExtras
  78. * @property {false | string | string[]} resource
  79. * @property {string=} resourceQuery
  80. * @property {string=} resourceFragment
  81. * @property {ResolveOptions=} resolveOptions
  82. */
  83. /** @typedef {ContextOptions & ContextModuleOptionsExtras} ContextModuleOptions */
  84. /**
  85. * @callback ResolveDependenciesCallback
  86. * @param {Error | null} err
  87. * @param {ContextElementDependency[]=} dependencies
  88. */
  89. /**
  90. * @callback ResolveDependencies
  91. * @param {InputFileSystem} fs
  92. * @param {ContextModuleOptions} options
  93. * @param {ResolveDependenciesCallback} callback
  94. */
  95. /** @typedef {1 | 3 | 7 | 9} FakeMapType */
  96. /** @typedef {Record<ModuleId, FakeMapType>} FakeMap */
  97. const SNAPSHOT_OPTIONS = { timestamp: true };
  98. class ContextModule extends Module {
  99. /**
  100. * @param {ResolveDependencies} resolveDependencies function to get dependencies in this context
  101. * @param {ContextModuleOptions} options options object
  102. */
  103. constructor(resolveDependencies, options) {
  104. if (!options || typeof options.resource === "string") {
  105. const parsed = parseResource(
  106. options ? /** @type {string} */ (options.resource) : ""
  107. );
  108. const resource = parsed.path;
  109. const resourceQuery = (options && options.resourceQuery) || parsed.query;
  110. const resourceFragment =
  111. (options && options.resourceFragment) || parsed.fragment;
  112. const layer = options && options.layer;
  113. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, resource, layer);
  114. /** @type {ContextModuleOptions} */
  115. this.options = {
  116. ...options,
  117. resource,
  118. resourceQuery,
  119. resourceFragment
  120. };
  121. } else {
  122. super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, undefined, options.layer);
  123. /** @type {ContextModuleOptions} */
  124. this.options = {
  125. ...options,
  126. resource: options.resource,
  127. resourceQuery: options.resourceQuery || "",
  128. resourceFragment: options.resourceFragment || ""
  129. };
  130. }
  131. // Info from Factory
  132. /** @type {ResolveDependencies | undefined} */
  133. this.resolveDependencies = resolveDependencies;
  134. if (options && options.resolveOptions !== undefined) {
  135. this.resolveOptions = options.resolveOptions;
  136. }
  137. if (options && typeof options.mode !== "string") {
  138. throw new Error("options.mode is a required option");
  139. }
  140. this._identifier = this._createIdentifier();
  141. this._forceBuild = true;
  142. }
  143. /**
  144. * @returns {SourceTypes} types available (do not mutate)
  145. */
  146. getSourceTypes() {
  147. return JS_TYPES;
  148. }
  149. /**
  150. * Assuming this module is in the cache. Update the (cached) module with
  151. * the fresh module from the factory. Usually updates internal references
  152. * and properties.
  153. * @param {Module} module fresh module
  154. * @returns {void}
  155. */
  156. updateCacheModule(module) {
  157. const m = /** @type {ContextModule} */ (module);
  158. this.resolveDependencies = m.resolveDependencies;
  159. this.options = m.options;
  160. }
  161. /**
  162. * Assuming this module is in the cache. Remove internal references to allow freeing some memory.
  163. */
  164. cleanupForCache() {
  165. super.cleanupForCache();
  166. this.resolveDependencies = undefined;
  167. }
  168. /**
  169. * @private
  170. * @param {RegExp} regexString RegExp as a string
  171. * @param {boolean=} stripSlash do we need to strip a slsh
  172. * @returns {string} pretty RegExp
  173. */
  174. _prettyRegExp(regexString, stripSlash = true) {
  175. const str = stripSlash
  176. ? regexString.source + regexString.flags
  177. : `${regexString}`;
  178. return str.replace(/!/g, "%21").replace(/\|/g, "%7C");
  179. }
  180. _createIdentifier() {
  181. let identifier =
  182. this.context ||
  183. (typeof this.options.resource === "string" ||
  184. this.options.resource === false
  185. ? `${this.options.resource}`
  186. : this.options.resource.join("|"));
  187. if (this.options.resourceQuery) {
  188. identifier += `|${this.options.resourceQuery}`;
  189. }
  190. if (this.options.resourceFragment) {
  191. identifier += `|${this.options.resourceFragment}`;
  192. }
  193. if (this.options.mode) {
  194. identifier += `|${this.options.mode}`;
  195. }
  196. if (!this.options.recursive) {
  197. identifier += "|nonrecursive";
  198. }
  199. if (this.options.addon) {
  200. identifier += `|${this.options.addon}`;
  201. }
  202. if (this.options.regExp) {
  203. identifier += `|${this._prettyRegExp(this.options.regExp, false)}`;
  204. }
  205. if (this.options.include) {
  206. identifier += `|include: ${this._prettyRegExp(
  207. this.options.include,
  208. false
  209. )}`;
  210. }
  211. if (this.options.exclude) {
  212. identifier += `|exclude: ${this._prettyRegExp(
  213. this.options.exclude,
  214. false
  215. )}`;
  216. }
  217. if (this.options.referencedExports) {
  218. identifier += `|referencedExports: ${JSON.stringify(
  219. this.options.referencedExports
  220. )}`;
  221. }
  222. if (this.options.chunkName) {
  223. identifier += `|chunkName: ${this.options.chunkName}`;
  224. }
  225. if (this.options.groupOptions) {
  226. identifier += `|groupOptions: ${JSON.stringify(
  227. this.options.groupOptions
  228. )}`;
  229. }
  230. if (this.options.namespaceObject === "strict") {
  231. identifier += "|strict namespace object";
  232. } else if (this.options.namespaceObject) {
  233. identifier += "|namespace object";
  234. }
  235. if (this.layer) {
  236. identifier += `|layer: ${this.layer}`;
  237. }
  238. return identifier;
  239. }
  240. /**
  241. * @returns {string} a unique identifier of the module
  242. */
  243. identifier() {
  244. return this._identifier;
  245. }
  246. /**
  247. * @param {RequestShortener} requestShortener the request shortener
  248. * @returns {string} a user readable identifier of the module
  249. */
  250. readableIdentifier(requestShortener) {
  251. let identifier;
  252. if (this.context) {
  253. identifier = `${requestShortener.shorten(this.context)}/`;
  254. } else if (
  255. typeof this.options.resource === "string" ||
  256. this.options.resource === false
  257. ) {
  258. identifier = `${requestShortener.shorten(`${this.options.resource}`)}/`;
  259. } else {
  260. identifier = this.options.resource
  261. .map(r => `${requestShortener.shorten(r)}/`)
  262. .join(" ");
  263. }
  264. if (this.options.resourceQuery) {
  265. identifier += ` ${this.options.resourceQuery}`;
  266. }
  267. if (this.options.mode) {
  268. identifier += ` ${this.options.mode}`;
  269. }
  270. if (!this.options.recursive) {
  271. identifier += " nonrecursive";
  272. }
  273. if (this.options.addon) {
  274. identifier += ` ${requestShortener.shorten(this.options.addon)}`;
  275. }
  276. if (this.options.regExp) {
  277. identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
  278. }
  279. if (this.options.include) {
  280. identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
  281. }
  282. if (this.options.exclude) {
  283. identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
  284. }
  285. if (this.options.referencedExports) {
  286. identifier += ` referencedExports: ${this.options.referencedExports
  287. .map(e => e.join("."))
  288. .join(", ")}`;
  289. }
  290. if (this.options.chunkName) {
  291. identifier += ` chunkName: ${this.options.chunkName}`;
  292. }
  293. if (this.options.groupOptions) {
  294. const groupOptions = this.options.groupOptions;
  295. for (const key of Object.keys(groupOptions)) {
  296. identifier += ` ${key}: ${
  297. groupOptions[/** @type {keyof RawChunkGroupOptions} */ (key)]
  298. }`;
  299. }
  300. }
  301. if (this.options.namespaceObject === "strict") {
  302. identifier += " strict namespace object";
  303. } else if (this.options.namespaceObject) {
  304. identifier += " namespace object";
  305. }
  306. return identifier;
  307. }
  308. /**
  309. * @param {LibIdentOptions} options options
  310. * @returns {string | null} an identifier for library inclusion
  311. */
  312. libIdent(options) {
  313. let identifier;
  314. if (this.context) {
  315. identifier = contextify(
  316. options.context,
  317. this.context,
  318. options.associatedObjectForCache
  319. );
  320. } else if (typeof this.options.resource === "string") {
  321. identifier = contextify(
  322. options.context,
  323. this.options.resource,
  324. options.associatedObjectForCache
  325. );
  326. } else if (this.options.resource === false) {
  327. identifier = "false";
  328. } else {
  329. identifier = this.options.resource
  330. .map(res =>
  331. contextify(options.context, res, options.associatedObjectForCache)
  332. )
  333. .join(" ");
  334. }
  335. if (this.layer) identifier = `(${this.layer})/${identifier}`;
  336. if (this.options.mode) {
  337. identifier += ` ${this.options.mode}`;
  338. }
  339. if (this.options.recursive) {
  340. identifier += " recursive";
  341. }
  342. if (this.options.addon) {
  343. identifier += ` ${contextify(
  344. options.context,
  345. this.options.addon,
  346. options.associatedObjectForCache
  347. )}`;
  348. }
  349. if (this.options.regExp) {
  350. identifier += ` ${this._prettyRegExp(this.options.regExp)}`;
  351. }
  352. if (this.options.include) {
  353. identifier += ` include: ${this._prettyRegExp(this.options.include)}`;
  354. }
  355. if (this.options.exclude) {
  356. identifier += ` exclude: ${this._prettyRegExp(this.options.exclude)}`;
  357. }
  358. if (this.options.referencedExports) {
  359. identifier += ` referencedExports: ${this.options.referencedExports
  360. .map(e => e.join("."))
  361. .join(", ")}`;
  362. }
  363. return identifier;
  364. }
  365. /**
  366. * @returns {void}
  367. */
  368. invalidateBuild() {
  369. this._forceBuild = true;
  370. }
  371. /**
  372. * @param {NeedBuildContext} context context info
  373. * @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
  374. * @returns {void}
  375. */
  376. needBuild({ fileSystemInfo }, callback) {
  377. // build if enforced
  378. if (this._forceBuild) return callback(null, true);
  379. const buildInfo = /** @type {BuildInfo} */ (this.buildInfo);
  380. // always build when we have no snapshot and context
  381. if (!buildInfo.snapshot)
  382. return callback(null, Boolean(this.context || this.options.resource));
  383. fileSystemInfo.checkSnapshotValid(buildInfo.snapshot, (err, valid) => {
  384. callback(err, !valid);
  385. });
  386. }
  387. /**
  388. * @param {WebpackOptions} options webpack options
  389. * @param {Compilation} compilation the compilation
  390. * @param {ResolverWithOptions} resolver the resolver
  391. * @param {InputFileSystem} fs the file system
  392. * @param {BuildCallback} callback callback function
  393. * @returns {void}
  394. */
  395. build(options, compilation, resolver, fs, callback) {
  396. this._forceBuild = false;
  397. /** @type {BuildMeta} */
  398. this.buildMeta = {
  399. exportsType: "default",
  400. defaultObject: "redirect-warn"
  401. };
  402. this.buildInfo = {
  403. snapshot: undefined
  404. };
  405. this.dependencies.length = 0;
  406. this.blocks.length = 0;
  407. const startTime = Date.now();
  408. /** @type {ResolveDependencies} */
  409. (this.resolveDependencies)(fs, this.options, (err, dependencies) => {
  410. if (err) {
  411. return callback(
  412. makeWebpackError(err, "ContextModule.resolveDependencies")
  413. );
  414. }
  415. // abort if something failed
  416. // this will create an empty context
  417. if (!dependencies) {
  418. callback();
  419. return;
  420. }
  421. // enhance dependencies with meta info
  422. for (const dep of dependencies) {
  423. dep.loc = {
  424. name: dep.userRequest
  425. };
  426. dep.request = this.options.addon + dep.request;
  427. }
  428. dependencies.sort(
  429. concatComparators(
  430. compareSelect(a => a.loc, compareLocations),
  431. keepOriginalOrder(this.dependencies)
  432. )
  433. );
  434. if (this.options.mode === "sync" || this.options.mode === "eager") {
  435. // if we have an sync or eager context
  436. // just add all dependencies and continue
  437. this.dependencies = dependencies;
  438. } else if (this.options.mode === "lazy-once") {
  439. // for the lazy-once mode create a new async dependency block
  440. // and add that block to this context
  441. if (dependencies.length > 0) {
  442. const block = new AsyncDependenciesBlock({
  443. ...this.options.groupOptions,
  444. name: this.options.chunkName
  445. });
  446. for (const dep of dependencies) {
  447. block.addDependency(dep);
  448. }
  449. this.addBlock(block);
  450. }
  451. } else if (
  452. this.options.mode === "weak" ||
  453. this.options.mode === "async-weak"
  454. ) {
  455. // we mark all dependencies as weak
  456. for (const dep of dependencies) {
  457. dep.weak = true;
  458. }
  459. this.dependencies = dependencies;
  460. } else if (this.options.mode === "lazy") {
  461. // if we are lazy create a new async dependency block per dependency
  462. // and add all blocks to this context
  463. let index = 0;
  464. for (const dep of dependencies) {
  465. let chunkName = this.options.chunkName;
  466. if (chunkName) {
  467. if (!/\[(index|request)\]/.test(chunkName)) {
  468. chunkName += "[index]";
  469. }
  470. chunkName = chunkName.replace(/\[index\]/g, `${index++}`);
  471. chunkName = chunkName.replace(
  472. /\[request\]/g,
  473. Template.toPath(dep.userRequest)
  474. );
  475. }
  476. const block = new AsyncDependenciesBlock(
  477. {
  478. ...this.options.groupOptions,
  479. name: chunkName
  480. },
  481. dep.loc,
  482. dep.userRequest
  483. );
  484. block.addDependency(dep);
  485. this.addBlock(block);
  486. }
  487. } else {
  488. callback(
  489. new WebpackError(`Unsupported mode "${this.options.mode}" in context`)
  490. );
  491. return;
  492. }
  493. if (!this.context && !this.options.resource) return callback();
  494. compilation.fileSystemInfo.createSnapshot(
  495. startTime,
  496. null,
  497. this.context
  498. ? [this.context]
  499. : typeof this.options.resource === "string"
  500. ? [this.options.resource]
  501. : /** @type {string[]} */ (this.options.resource),
  502. null,
  503. SNAPSHOT_OPTIONS,
  504. (err, snapshot) => {
  505. if (err) return callback(err);
  506. /** @type {BuildInfo} */
  507. (this.buildInfo).snapshot = snapshot;
  508. callback();
  509. }
  510. );
  511. });
  512. }
  513. /**
  514. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  515. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  516. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  517. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  518. */
  519. addCacheDependencies(
  520. fileDependencies,
  521. contextDependencies,
  522. missingDependencies,
  523. buildDependencies
  524. ) {
  525. if (this.context) {
  526. contextDependencies.add(this.context);
  527. } else if (typeof this.options.resource === "string") {
  528. contextDependencies.add(this.options.resource);
  529. } else if (this.options.resource === false) {
  530. // Do nothing
  531. } else {
  532. for (const res of this.options.resource) contextDependencies.add(res);
  533. }
  534. }
  535. /**
  536. * @param {Dependency[]} dependencies all dependencies
  537. * @param {ChunkGraph} chunkGraph chunk graph
  538. * @returns {Map<string, string | number>} map with user requests
  539. */
  540. getUserRequestMap(dependencies, chunkGraph) {
  541. const moduleGraph = chunkGraph.moduleGraph;
  542. // if we filter first we get a new array
  543. // therefore we don't need to create a clone of dependencies explicitly
  544. // therefore the order of this is !important!
  545. const sortedDependencies =
  546. /** @type {ContextElementDependency[]} */
  547. (dependencies)
  548. .filter(dependency => moduleGraph.getModule(dependency))
  549. .sort((a, b) => {
  550. if (a.userRequest === b.userRequest) {
  551. return 0;
  552. }
  553. return a.userRequest < b.userRequest ? -1 : 1;
  554. });
  555. const map = Object.create(null);
  556. for (const dep of sortedDependencies) {
  557. const module = /** @type {Module} */ (moduleGraph.getModule(dep));
  558. map[dep.userRequest] = chunkGraph.getModuleId(module);
  559. }
  560. return map;
  561. }
  562. /**
  563. * @param {Dependency[]} dependencies all dependencies
  564. * @param {ChunkGraph} chunkGraph chunk graph
  565. * @returns {FakeMap | FakeMapType} fake map
  566. */
  567. getFakeMap(dependencies, chunkGraph) {
  568. if (!this.options.namespaceObject) {
  569. return 9;
  570. }
  571. const moduleGraph = chunkGraph.moduleGraph;
  572. // bitfield
  573. let hasType = 0;
  574. const comparator = compareModulesById(chunkGraph);
  575. // if we filter first we get a new array
  576. // therefore we don't need to create a clone of dependencies explicitly
  577. // therefore the order of this is !important!
  578. const sortedModules = dependencies
  579. .map(
  580. dependency => /** @type {Module} */ (moduleGraph.getModule(dependency))
  581. )
  582. .filter(Boolean)
  583. .sort(comparator);
  584. /** @type {FakeMap} */
  585. const fakeMap = Object.create(null);
  586. for (const module of sortedModules) {
  587. const exportsType = module.getExportsType(
  588. moduleGraph,
  589. this.options.namespaceObject === "strict"
  590. );
  591. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
  592. switch (exportsType) {
  593. case "namespace":
  594. fakeMap[id] = 9;
  595. hasType |= 1;
  596. break;
  597. case "dynamic":
  598. fakeMap[id] = 7;
  599. hasType |= 2;
  600. break;
  601. case "default-only":
  602. fakeMap[id] = 1;
  603. hasType |= 4;
  604. break;
  605. case "default-with-named":
  606. fakeMap[id] = 3;
  607. hasType |= 8;
  608. break;
  609. default:
  610. throw new Error(`Unexpected exports type ${exportsType}`);
  611. }
  612. }
  613. if (hasType === 1) {
  614. return 9;
  615. }
  616. if (hasType === 2) {
  617. return 7;
  618. }
  619. if (hasType === 4) {
  620. return 1;
  621. }
  622. if (hasType === 8) {
  623. return 3;
  624. }
  625. if (hasType === 0) {
  626. return 9;
  627. }
  628. return fakeMap;
  629. }
  630. /**
  631. * @param {FakeMap | FakeMapType} fakeMap fake map
  632. * @returns {string} fake map init statement
  633. */
  634. getFakeMapInitStatement(fakeMap) {
  635. return typeof fakeMap === "object"
  636. ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};`
  637. : "";
  638. }
  639. /**
  640. * @param {FakeMapType} type type
  641. * @param {boolean=} asyncModule is async module
  642. * @returns {string} return result
  643. */
  644. getReturn(type, asyncModule) {
  645. if (type === 9) {
  646. return `${RuntimeGlobals.require}(id)`;
  647. }
  648. return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${
  649. asyncModule ? " | 16" : ""
  650. })`;
  651. }
  652. /**
  653. * @param {FakeMap | FakeMapType} fakeMap fake map
  654. * @param {boolean=} asyncModule us async module
  655. * @param {string=} fakeMapDataExpression fake map data expression
  656. * @returns {string} module object source
  657. */
  658. getReturnModuleObjectSource(
  659. fakeMap,
  660. asyncModule,
  661. fakeMapDataExpression = "fakeMap[id]"
  662. ) {
  663. if (typeof fakeMap === "number") {
  664. return `return ${this.getReturn(fakeMap, asyncModule)};`;
  665. }
  666. return `return ${
  667. RuntimeGlobals.createFakeNamespaceObject
  668. }(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`;
  669. }
  670. /**
  671. * @param {Dependency[]} dependencies dependencies
  672. * @param {ModuleId} id module id
  673. * @param {ChunkGraph} chunkGraph the chunk graph
  674. * @returns {string} source code
  675. */
  676. getSyncSource(dependencies, id, chunkGraph) {
  677. const map = this.getUserRequestMap(dependencies, chunkGraph);
  678. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  679. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
  680. return `var map = ${JSON.stringify(map, null, "\t")};
  681. ${this.getFakeMapInitStatement(fakeMap)}
  682. function webpackContext(req) {
  683. var id = webpackContextResolve(req);
  684. ${returnModuleObject}
  685. }
  686. function webpackContextResolve(req) {
  687. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  688. var e = new Error("Cannot find module '" + req + "'");
  689. e.code = 'MODULE_NOT_FOUND';
  690. throw e;
  691. }
  692. return map[req];
  693. }
  694. webpackContext.keys = function webpackContextKeys() {
  695. return Object.keys(map);
  696. };
  697. webpackContext.resolve = webpackContextResolve;
  698. module.exports = webpackContext;
  699. webpackContext.id = ${JSON.stringify(id)};`;
  700. }
  701. /**
  702. * @param {Dependency[]} dependencies dependencies
  703. * @param {ModuleId} id module id
  704. * @param {ChunkGraph} chunkGraph the chunk graph
  705. * @returns {string} source code
  706. */
  707. getWeakSyncSource(dependencies, id, chunkGraph) {
  708. const map = this.getUserRequestMap(dependencies, chunkGraph);
  709. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  710. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
  711. return `var map = ${JSON.stringify(map, null, "\t")};
  712. ${this.getFakeMapInitStatement(fakeMap)}
  713. function webpackContext(req) {
  714. var id = webpackContextResolve(req);
  715. if(!${RuntimeGlobals.moduleFactories}[id]) {
  716. var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
  717. e.code = 'MODULE_NOT_FOUND';
  718. throw e;
  719. }
  720. ${returnModuleObject}
  721. }
  722. function webpackContextResolve(req) {
  723. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  724. var e = new Error("Cannot find module '" + req + "'");
  725. e.code = 'MODULE_NOT_FOUND';
  726. throw e;
  727. }
  728. return map[req];
  729. }
  730. webpackContext.keys = function webpackContextKeys() {
  731. return Object.keys(map);
  732. };
  733. webpackContext.resolve = webpackContextResolve;
  734. webpackContext.id = ${JSON.stringify(id)};
  735. module.exports = webpackContext;`;
  736. }
  737. /**
  738. * @param {Dependency[]} dependencies dependencies
  739. * @param {ModuleId} id module id
  740. * @param {object} context context
  741. * @param {ChunkGraph} context.chunkGraph the chunk graph
  742. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  743. * @returns {string} source code
  744. */
  745. getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
  746. const arrow = runtimeTemplate.supportsArrowFunction();
  747. const map = this.getUserRequestMap(dependencies, chunkGraph);
  748. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  749. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true);
  750. return `var map = ${JSON.stringify(map, null, "\t")};
  751. ${this.getFakeMapInitStatement(fakeMap)}
  752. function webpackAsyncContext(req) {
  753. return webpackAsyncContextResolve(req).then(${
  754. arrow ? "id =>" : "function(id)"
  755. } {
  756. if(!${RuntimeGlobals.moduleFactories}[id]) {
  757. var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
  758. e.code = 'MODULE_NOT_FOUND';
  759. throw e;
  760. }
  761. ${returnModuleObject}
  762. });
  763. }
  764. function webpackAsyncContextResolve(req) {
  765. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  766. // uncaught exception popping up in devtools
  767. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  768. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  769. var e = new Error("Cannot find module '" + req + "'");
  770. e.code = 'MODULE_NOT_FOUND';
  771. throw e;
  772. }
  773. return map[req];
  774. });
  775. }
  776. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  777. "Object.keys(map)"
  778. )};
  779. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  780. webpackAsyncContext.id = ${JSON.stringify(id)};
  781. module.exports = webpackAsyncContext;`;
  782. }
  783. /**
  784. * @param {Dependency[]} dependencies dependencies
  785. * @param {ModuleId} id module id
  786. * @param {object} context context
  787. * @param {ChunkGraph} context.chunkGraph the chunk graph
  788. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  789. * @returns {string} source code
  790. */
  791. getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
  792. const arrow = runtimeTemplate.supportsArrowFunction();
  793. const map = this.getUserRequestMap(dependencies, chunkGraph);
  794. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  795. const thenFunction =
  796. fakeMap !== 9
  797. ? `${arrow ? "id =>" : "function(id)"} {
  798. ${this.getReturnModuleObjectSource(fakeMap, true)}
  799. }`
  800. : RuntimeGlobals.require;
  801. return `var map = ${JSON.stringify(map, null, "\t")};
  802. ${this.getFakeMapInitStatement(fakeMap)}
  803. function webpackAsyncContext(req) {
  804. return webpackAsyncContextResolve(req).then(${thenFunction});
  805. }
  806. function webpackAsyncContextResolve(req) {
  807. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  808. // uncaught exception popping up in devtools
  809. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  810. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  811. var e = new Error("Cannot find module '" + req + "'");
  812. e.code = 'MODULE_NOT_FOUND';
  813. throw e;
  814. }
  815. return map[req];
  816. });
  817. }
  818. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  819. "Object.keys(map)"
  820. )};
  821. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  822. webpackAsyncContext.id = ${JSON.stringify(id)};
  823. module.exports = webpackAsyncContext;`;
  824. }
  825. /**
  826. * @param {AsyncDependenciesBlock} block block
  827. * @param {Dependency[]} dependencies dependencies
  828. * @param {ModuleId} id module id
  829. * @param {object} options options object
  830. * @param {RuntimeTemplate} options.runtimeTemplate the runtime template
  831. * @param {ChunkGraph} options.chunkGraph the chunk graph
  832. * @returns {string} source code
  833. */
  834. getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) {
  835. const promise = runtimeTemplate.blockPromise({
  836. chunkGraph,
  837. block,
  838. message: "lazy-once context",
  839. runtimeRequirements: new Set()
  840. });
  841. const arrow = runtimeTemplate.supportsArrowFunction();
  842. const map = this.getUserRequestMap(dependencies, chunkGraph);
  843. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  844. const thenFunction =
  845. fakeMap !== 9
  846. ? `${arrow ? "id =>" : "function(id)"} {
  847. ${this.getReturnModuleObjectSource(fakeMap, true)};
  848. }`
  849. : RuntimeGlobals.require;
  850. return `var map = ${JSON.stringify(map, null, "\t")};
  851. ${this.getFakeMapInitStatement(fakeMap)}
  852. function webpackAsyncContext(req) {
  853. return webpackAsyncContextResolve(req).then(${thenFunction});
  854. }
  855. function webpackAsyncContextResolve(req) {
  856. return ${promise}.then(${arrow ? "() =>" : "function()"} {
  857. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  858. var e = new Error("Cannot find module '" + req + "'");
  859. e.code = 'MODULE_NOT_FOUND';
  860. throw e;
  861. }
  862. return map[req];
  863. });
  864. }
  865. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  866. "Object.keys(map)"
  867. )};
  868. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  869. webpackAsyncContext.id = ${JSON.stringify(id)};
  870. module.exports = webpackAsyncContext;`;
  871. }
  872. /**
  873. * @param {AsyncDependenciesBlock[]} blocks blocks
  874. * @param {ModuleId} id module id
  875. * @param {object} context context
  876. * @param {ChunkGraph} context.chunkGraph the chunk graph
  877. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  878. * @returns {string} source code
  879. */
  880. getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) {
  881. const moduleGraph = chunkGraph.moduleGraph;
  882. const arrow = runtimeTemplate.supportsArrowFunction();
  883. let hasMultipleOrNoChunks = false;
  884. let hasNoChunk = true;
  885. const fakeMap = this.getFakeMap(
  886. blocks.map(b => b.dependencies[0]),
  887. chunkGraph
  888. );
  889. const hasFakeMap = typeof fakeMap === "object";
  890. /** @typedef {{userRequest: string, dependency: ContextElementDependency, chunks: undefined | Chunk[], module: Module, block: AsyncDependenciesBlock}} Item */
  891. /**
  892. * @type {Item[]}
  893. */
  894. const items = blocks
  895. .map(block => {
  896. const dependency =
  897. /** @type {ContextElementDependency} */
  898. (block.dependencies[0]);
  899. return {
  900. dependency,
  901. module: /** @type {Module} */ (moduleGraph.getModule(dependency)),
  902. block,
  903. userRequest: dependency.userRequest,
  904. chunks: undefined
  905. };
  906. })
  907. .filter(item => item.module);
  908. for (const item of items) {
  909. const chunkGroup = chunkGraph.getBlockChunkGroup(item.block);
  910. const chunks = (chunkGroup && chunkGroup.chunks) || [];
  911. item.chunks = chunks;
  912. if (chunks.length > 0) {
  913. hasNoChunk = false;
  914. }
  915. if (chunks.length !== 1) {
  916. hasMultipleOrNoChunks = true;
  917. }
  918. }
  919. const shortMode = hasNoChunk && !hasFakeMap;
  920. const sortedItems = items.sort((a, b) => {
  921. if (a.userRequest === b.userRequest) return 0;
  922. return a.userRequest < b.userRequest ? -1 : 1;
  923. });
  924. /** @type {Record<string, ModuleId | (ModuleId[] | ChunkId[])>} */
  925. const map = Object.create(null);
  926. for (const item of sortedItems) {
  927. const moduleId =
  928. /** @type {ModuleId} */
  929. (chunkGraph.getModuleId(item.module));
  930. if (shortMode) {
  931. map[item.userRequest] = moduleId;
  932. } else {
  933. /** @type {(ModuleId | ChunkId)[]} */
  934. const arrayStart = [moduleId];
  935. if (hasFakeMap) {
  936. arrayStart.push(fakeMap[moduleId]);
  937. }
  938. map[item.userRequest] = arrayStart.concat(
  939. /** @type {Chunk[]} */
  940. (item.chunks).map(chunk => /** @type {ChunkId} */ (chunk.id))
  941. );
  942. }
  943. }
  944. const chunksStartPosition = hasFakeMap ? 2 : 1;
  945. const requestPrefix = hasNoChunk
  946. ? "Promise.resolve()"
  947. : hasMultipleOrNoChunks
  948. ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))`
  949. : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`;
  950. const returnModuleObject = this.getReturnModuleObjectSource(
  951. fakeMap,
  952. true,
  953. shortMode ? "invalid" : "ids[1]"
  954. );
  955. const webpackAsyncContext =
  956. requestPrefix === "Promise.resolve()"
  957. ? `
  958. function webpackAsyncContext(req) {
  959. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  960. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  961. var e = new Error("Cannot find module '" + req + "'");
  962. e.code = 'MODULE_NOT_FOUND';
  963. throw e;
  964. }
  965. ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"}
  966. ${returnModuleObject}
  967. });
  968. }`
  969. : `function webpackAsyncContext(req) {
  970. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  971. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  972. var e = new Error("Cannot find module '" + req + "'");
  973. e.code = 'MODULE_NOT_FOUND';
  974. throw e;
  975. });
  976. }
  977. var ids = map[req], id = ids[0];
  978. return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} {
  979. ${returnModuleObject}
  980. });
  981. }`;
  982. return `var map = ${JSON.stringify(map, null, "\t")};
  983. ${webpackAsyncContext}
  984. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  985. "Object.keys(map)"
  986. )};
  987. webpackAsyncContext.id = ${JSON.stringify(id)};
  988. module.exports = webpackAsyncContext;`;
  989. }
  990. /**
  991. * @param {ModuleId} id module id
  992. * @param {RuntimeTemplate} runtimeTemplate runtime template
  993. * @returns {string} source for empty async context
  994. */
  995. getSourceForEmptyContext(id, runtimeTemplate) {
  996. return `function webpackEmptyContext(req) {
  997. var e = new Error("Cannot find module '" + req + "'");
  998. e.code = 'MODULE_NOT_FOUND';
  999. throw e;
  1000. }
  1001. webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")};
  1002. webpackEmptyContext.resolve = webpackEmptyContext;
  1003. webpackEmptyContext.id = ${JSON.stringify(id)};
  1004. module.exports = webpackEmptyContext;`;
  1005. }
  1006. /**
  1007. * @param {ModuleId} id module id
  1008. * @param {RuntimeTemplate} runtimeTemplate runtime template
  1009. * @returns {string} source for empty async context
  1010. */
  1011. getSourceForEmptyAsyncContext(id, runtimeTemplate) {
  1012. const arrow = runtimeTemplate.supportsArrowFunction();
  1013. return `function webpackEmptyAsyncContext(req) {
  1014. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  1015. // uncaught exception popping up in devtools
  1016. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  1017. var e = new Error("Cannot find module '" + req + "'");
  1018. e.code = 'MODULE_NOT_FOUND';
  1019. throw e;
  1020. });
  1021. }
  1022. webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")};
  1023. webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
  1024. webpackEmptyAsyncContext.id = ${JSON.stringify(id)};
  1025. module.exports = webpackEmptyAsyncContext;`;
  1026. }
  1027. /**
  1028. * @param {string} asyncMode module mode
  1029. * @param {CodeGenerationContext} context context info
  1030. * @returns {string} the source code
  1031. */
  1032. getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) {
  1033. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(this));
  1034. if (asyncMode === "lazy") {
  1035. if (this.blocks && this.blocks.length > 0) {
  1036. return this.getLazySource(this.blocks, id, {
  1037. runtimeTemplate,
  1038. chunkGraph
  1039. });
  1040. }
  1041. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1042. }
  1043. if (asyncMode === "eager") {
  1044. if (this.dependencies && this.dependencies.length > 0) {
  1045. return this.getEagerSource(this.dependencies, id, {
  1046. chunkGraph,
  1047. runtimeTemplate
  1048. });
  1049. }
  1050. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1051. }
  1052. if (asyncMode === "lazy-once") {
  1053. const block = this.blocks[0];
  1054. if (block) {
  1055. return this.getLazyOnceSource(block, block.dependencies, id, {
  1056. runtimeTemplate,
  1057. chunkGraph
  1058. });
  1059. }
  1060. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1061. }
  1062. if (asyncMode === "async-weak") {
  1063. if (this.dependencies && this.dependencies.length > 0) {
  1064. return this.getAsyncWeakSource(this.dependencies, id, {
  1065. chunkGraph,
  1066. runtimeTemplate
  1067. });
  1068. }
  1069. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1070. }
  1071. if (
  1072. asyncMode === "weak" &&
  1073. this.dependencies &&
  1074. this.dependencies.length > 0
  1075. ) {
  1076. return this.getWeakSyncSource(this.dependencies, id, chunkGraph);
  1077. }
  1078. if (this.dependencies && this.dependencies.length > 0) {
  1079. return this.getSyncSource(this.dependencies, id, chunkGraph);
  1080. }
  1081. return this.getSourceForEmptyContext(id, runtimeTemplate);
  1082. }
  1083. /**
  1084. * @param {string} sourceString source content
  1085. * @param {Compilation=} compilation the compilation
  1086. * @returns {Source} generated source
  1087. */
  1088. getSource(sourceString, compilation) {
  1089. if (this.useSourceMap || this.useSimpleSourceMap) {
  1090. return new OriginalSource(
  1091. sourceString,
  1092. `webpack://${makePathsRelative(
  1093. (compilation && compilation.compiler.context) || "",
  1094. this.identifier(),
  1095. compilation && compilation.compiler.root
  1096. )}`
  1097. );
  1098. }
  1099. return new RawSource(sourceString);
  1100. }
  1101. /**
  1102. * @param {CodeGenerationContext} context context for code generation
  1103. * @returns {CodeGenerationResult} result
  1104. */
  1105. codeGeneration(context) {
  1106. const { chunkGraph, compilation } = context;
  1107. const sources = new Map();
  1108. sources.set(
  1109. "javascript",
  1110. this.getSource(
  1111. this.getSourceString(this.options.mode, context),
  1112. compilation
  1113. )
  1114. );
  1115. const set = new Set();
  1116. const allDeps =
  1117. this.dependencies.length > 0
  1118. ? /** @type {ContextElementDependency[]} */ (this.dependencies).slice()
  1119. : [];
  1120. for (const block of this.blocks)
  1121. for (const dep of block.dependencies)
  1122. allDeps.push(/** @type {ContextElementDependency} */ (dep));
  1123. set.add(RuntimeGlobals.module);
  1124. set.add(RuntimeGlobals.hasOwnProperty);
  1125. if (allDeps.length > 0) {
  1126. const asyncMode = this.options.mode;
  1127. set.add(RuntimeGlobals.require);
  1128. if (asyncMode === "weak") {
  1129. set.add(RuntimeGlobals.moduleFactories);
  1130. } else if (asyncMode === "async-weak") {
  1131. set.add(RuntimeGlobals.moduleFactories);
  1132. set.add(RuntimeGlobals.ensureChunk);
  1133. } else if (asyncMode === "lazy" || asyncMode === "lazy-once") {
  1134. set.add(RuntimeGlobals.ensureChunk);
  1135. }
  1136. if (this.getFakeMap(allDeps, chunkGraph) !== 9) {
  1137. set.add(RuntimeGlobals.createFakeNamespaceObject);
  1138. }
  1139. }
  1140. return {
  1141. sources,
  1142. runtimeRequirements: set
  1143. };
  1144. }
  1145. /**
  1146. * @param {string=} type the source type for which the size should be estimated
  1147. * @returns {number} the estimated size of the module (must be non-zero)
  1148. */
  1149. size(type) {
  1150. // base penalty
  1151. let size = 160;
  1152. // if we don't have dependencies we stop here.
  1153. for (const dependency of this.dependencies) {
  1154. const element = /** @type {ContextElementDependency} */ (dependency);
  1155. size += 5 + element.userRequest.length;
  1156. }
  1157. return size;
  1158. }
  1159. /**
  1160. * @param {ObjectSerializerContext} context context
  1161. */
  1162. serialize(context) {
  1163. const { write } = context;
  1164. write(this._identifier);
  1165. write(this._forceBuild);
  1166. super.serialize(context);
  1167. }
  1168. /**
  1169. * @param {ObjectDeserializerContext} context context
  1170. */
  1171. deserialize(context) {
  1172. const { read } = context;
  1173. this._identifier = read();
  1174. this._forceBuild = read();
  1175. super.deserialize(context);
  1176. }
  1177. }
  1178. makeSerializable(ContextModule, "webpack/lib/ContextModule");
  1179. module.exports = ContextModule;