ContextModule.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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. compareModulesById,
  18. compareSelect,
  19. concatComparators,
  20. keepOriginalOrder
  21. } = require("./util/comparators");
  22. const {
  23. contextify,
  24. makePathsRelative,
  25. parseResource
  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. }
  384. fileSystemInfo.checkSnapshotValid(buildInfo.snapshot, (err, valid) => {
  385. callback(err, !valid);
  386. });
  387. }
  388. /**
  389. * @param {WebpackOptions} options webpack options
  390. * @param {Compilation} compilation the compilation
  391. * @param {ResolverWithOptions} resolver the resolver
  392. * @param {InputFileSystem} fs the file system
  393. * @param {BuildCallback} callback callback function
  394. * @returns {void}
  395. */
  396. build(options, compilation, resolver, fs, callback) {
  397. this._forceBuild = false;
  398. /** @type {BuildMeta} */
  399. this.buildMeta = {
  400. exportsType: "default",
  401. defaultObject: "redirect-warn"
  402. };
  403. this.buildInfo = {
  404. snapshot: undefined
  405. };
  406. this.dependencies.length = 0;
  407. this.blocks.length = 0;
  408. const startTime = Date.now();
  409. /** @type {ResolveDependencies} */
  410. (this.resolveDependencies)(fs, this.options, (err, dependencies) => {
  411. if (err) {
  412. return callback(
  413. makeWebpackError(err, "ContextModule.resolveDependencies")
  414. );
  415. }
  416. // abort if something failed
  417. // this will create an empty context
  418. if (!dependencies) {
  419. callback();
  420. return;
  421. }
  422. // enhance dependencies with meta info
  423. for (const dep of dependencies) {
  424. dep.loc = {
  425. name: dep.userRequest
  426. };
  427. dep.request = this.options.addon + dep.request;
  428. }
  429. dependencies.sort(
  430. concatComparators(
  431. compareSelect(a => a.loc, compareLocations),
  432. keepOriginalOrder(this.dependencies)
  433. )
  434. );
  435. if (this.options.mode === "sync" || this.options.mode === "eager") {
  436. // if we have an sync or eager context
  437. // just add all dependencies and continue
  438. this.dependencies = dependencies;
  439. } else if (this.options.mode === "lazy-once") {
  440. // for the lazy-once mode create a new async dependency block
  441. // and add that block to this context
  442. if (dependencies.length > 0) {
  443. const block = new AsyncDependenciesBlock({
  444. ...this.options.groupOptions,
  445. name: this.options.chunkName
  446. });
  447. for (const dep of dependencies) {
  448. block.addDependency(dep);
  449. }
  450. this.addBlock(block);
  451. }
  452. } else if (
  453. this.options.mode === "weak" ||
  454. this.options.mode === "async-weak"
  455. ) {
  456. // we mark all dependencies as weak
  457. for (const dep of dependencies) {
  458. dep.weak = true;
  459. }
  460. this.dependencies = dependencies;
  461. } else if (this.options.mode === "lazy") {
  462. // if we are lazy create a new async dependency block per dependency
  463. // and add all blocks to this context
  464. let index = 0;
  465. for (const dep of dependencies) {
  466. let chunkName = this.options.chunkName;
  467. if (chunkName) {
  468. if (!/\[(index|request)\]/.test(chunkName)) {
  469. chunkName += "[index]";
  470. }
  471. chunkName = chunkName.replace(/\[index\]/g, `${index++}`);
  472. chunkName = chunkName.replace(
  473. /\[request\]/g,
  474. Template.toPath(dep.userRequest)
  475. );
  476. }
  477. const block = new AsyncDependenciesBlock(
  478. {
  479. ...this.options.groupOptions,
  480. name: chunkName
  481. },
  482. dep.loc,
  483. dep.userRequest
  484. );
  485. block.addDependency(dep);
  486. this.addBlock(block);
  487. }
  488. } else {
  489. callback(
  490. new WebpackError(`Unsupported mode "${this.options.mode}" in context`)
  491. );
  492. return;
  493. }
  494. if (!this.context && !this.options.resource) return callback();
  495. compilation.fileSystemInfo.createSnapshot(
  496. startTime,
  497. null,
  498. this.context
  499. ? [this.context]
  500. : typeof this.options.resource === "string"
  501. ? [this.options.resource]
  502. : /** @type {string[]} */ (this.options.resource),
  503. null,
  504. SNAPSHOT_OPTIONS,
  505. (err, snapshot) => {
  506. if (err) return callback(err);
  507. /** @type {BuildInfo} */
  508. (this.buildInfo).snapshot = snapshot;
  509. callback();
  510. }
  511. );
  512. });
  513. }
  514. /**
  515. * @param {LazySet<string>} fileDependencies set where file dependencies are added to
  516. * @param {LazySet<string>} contextDependencies set where context dependencies are added to
  517. * @param {LazySet<string>} missingDependencies set where missing dependencies are added to
  518. * @param {LazySet<string>} buildDependencies set where build dependencies are added to
  519. */
  520. addCacheDependencies(
  521. fileDependencies,
  522. contextDependencies,
  523. missingDependencies,
  524. buildDependencies
  525. ) {
  526. if (this.context) {
  527. contextDependencies.add(this.context);
  528. } else if (typeof this.options.resource === "string") {
  529. contextDependencies.add(this.options.resource);
  530. } else if (this.options.resource === false) {
  531. // Do nothing
  532. } else {
  533. for (const res of this.options.resource) contextDependencies.add(res);
  534. }
  535. }
  536. /**
  537. * @param {Dependency[]} dependencies all dependencies
  538. * @param {ChunkGraph} chunkGraph chunk graph
  539. * @returns {Map<string, string | number>} map with user requests
  540. */
  541. getUserRequestMap(dependencies, chunkGraph) {
  542. const moduleGraph = chunkGraph.moduleGraph;
  543. // if we filter first we get a new array
  544. // therefore we don't need to create a clone of dependencies explicitly
  545. // therefore the order of this is !important!
  546. const sortedDependencies =
  547. /** @type {ContextElementDependency[]} */
  548. (dependencies)
  549. .filter(dependency => moduleGraph.getModule(dependency))
  550. .sort((a, b) => {
  551. if (a.userRequest === b.userRequest) {
  552. return 0;
  553. }
  554. return a.userRequest < b.userRequest ? -1 : 1;
  555. });
  556. const map = Object.create(null);
  557. for (const dep of sortedDependencies) {
  558. const module = /** @type {Module} */ (moduleGraph.getModule(dep));
  559. map[dep.userRequest] = chunkGraph.getModuleId(module);
  560. }
  561. return map;
  562. }
  563. /**
  564. * @param {Dependency[]} dependencies all dependencies
  565. * @param {ChunkGraph} chunkGraph chunk graph
  566. * @returns {FakeMap | FakeMapType} fake map
  567. */
  568. getFakeMap(dependencies, chunkGraph) {
  569. if (!this.options.namespaceObject) {
  570. return 9;
  571. }
  572. const moduleGraph = chunkGraph.moduleGraph;
  573. // bitfield
  574. let hasType = 0;
  575. const comparator = compareModulesById(chunkGraph);
  576. // if we filter first we get a new array
  577. // therefore we don't need to create a clone of dependencies explicitly
  578. // therefore the order of this is !important!
  579. const sortedModules = dependencies
  580. .map(
  581. dependency => /** @type {Module} */ (moduleGraph.getModule(dependency))
  582. )
  583. .filter(Boolean)
  584. .sort(comparator);
  585. /** @type {FakeMap} */
  586. const fakeMap = Object.create(null);
  587. for (const module of sortedModules) {
  588. const exportsType = module.getExportsType(
  589. moduleGraph,
  590. this.options.namespaceObject === "strict"
  591. );
  592. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(module));
  593. switch (exportsType) {
  594. case "namespace":
  595. fakeMap[id] = 9;
  596. hasType |= 1;
  597. break;
  598. case "dynamic":
  599. fakeMap[id] = 7;
  600. hasType |= 2;
  601. break;
  602. case "default-only":
  603. fakeMap[id] = 1;
  604. hasType |= 4;
  605. break;
  606. case "default-with-named":
  607. fakeMap[id] = 3;
  608. hasType |= 8;
  609. break;
  610. default:
  611. throw new Error(`Unexpected exports type ${exportsType}`);
  612. }
  613. }
  614. if (hasType === 1) {
  615. return 9;
  616. }
  617. if (hasType === 2) {
  618. return 7;
  619. }
  620. if (hasType === 4) {
  621. return 1;
  622. }
  623. if (hasType === 8) {
  624. return 3;
  625. }
  626. if (hasType === 0) {
  627. return 9;
  628. }
  629. return fakeMap;
  630. }
  631. /**
  632. * @param {FakeMap | FakeMapType} fakeMap fake map
  633. * @returns {string} fake map init statement
  634. */
  635. getFakeMapInitStatement(fakeMap) {
  636. return typeof fakeMap === "object"
  637. ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};`
  638. : "";
  639. }
  640. /**
  641. * @param {FakeMapType} type type
  642. * @param {boolean=} asyncModule is async module
  643. * @returns {string} return result
  644. */
  645. getReturn(type, asyncModule) {
  646. if (type === 9) {
  647. return `${RuntimeGlobals.require}(id)`;
  648. }
  649. return `${RuntimeGlobals.createFakeNamespaceObject}(id, ${type}${
  650. asyncModule ? " | 16" : ""
  651. })`;
  652. }
  653. /**
  654. * @param {FakeMap | FakeMapType} fakeMap fake map
  655. * @param {boolean=} asyncModule us async module
  656. * @param {string=} fakeMapDataExpression fake map data expression
  657. * @returns {string} module object source
  658. */
  659. getReturnModuleObjectSource(
  660. fakeMap,
  661. asyncModule,
  662. fakeMapDataExpression = "fakeMap[id]"
  663. ) {
  664. if (typeof fakeMap === "number") {
  665. return `return ${this.getReturn(fakeMap, asyncModule)};`;
  666. }
  667. return `return ${
  668. RuntimeGlobals.createFakeNamespaceObject
  669. }(id, ${fakeMapDataExpression}${asyncModule ? " | 16" : ""})`;
  670. }
  671. /**
  672. * @param {Dependency[]} dependencies dependencies
  673. * @param {ModuleId} id module id
  674. * @param {ChunkGraph} chunkGraph the chunk graph
  675. * @returns {string} source code
  676. */
  677. getSyncSource(dependencies, id, chunkGraph) {
  678. const map = this.getUserRequestMap(dependencies, chunkGraph);
  679. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  680. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
  681. return `var map = ${JSON.stringify(map, null, "\t")};
  682. ${this.getFakeMapInitStatement(fakeMap)}
  683. function webpackContext(req) {
  684. var id = webpackContextResolve(req);
  685. ${returnModuleObject}
  686. }
  687. function webpackContextResolve(req) {
  688. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  689. var e = new Error("Cannot find module '" + req + "'");
  690. e.code = 'MODULE_NOT_FOUND';
  691. throw e;
  692. }
  693. return map[req];
  694. }
  695. webpackContext.keys = function webpackContextKeys() {
  696. return Object.keys(map);
  697. };
  698. webpackContext.resolve = webpackContextResolve;
  699. module.exports = webpackContext;
  700. webpackContext.id = ${JSON.stringify(id)};`;
  701. }
  702. /**
  703. * @param {Dependency[]} dependencies dependencies
  704. * @param {ModuleId} id module id
  705. * @param {ChunkGraph} chunkGraph the chunk graph
  706. * @returns {string} source code
  707. */
  708. getWeakSyncSource(dependencies, id, chunkGraph) {
  709. const map = this.getUserRequestMap(dependencies, chunkGraph);
  710. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  711. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap);
  712. return `var map = ${JSON.stringify(map, null, "\t")};
  713. ${this.getFakeMapInitStatement(fakeMap)}
  714. function webpackContext(req) {
  715. var id = webpackContextResolve(req);
  716. if(!${RuntimeGlobals.moduleFactories}[id]) {
  717. var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
  718. e.code = 'MODULE_NOT_FOUND';
  719. throw e;
  720. }
  721. ${returnModuleObject}
  722. }
  723. function webpackContextResolve(req) {
  724. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  725. var e = new Error("Cannot find module '" + req + "'");
  726. e.code = 'MODULE_NOT_FOUND';
  727. throw e;
  728. }
  729. return map[req];
  730. }
  731. webpackContext.keys = function webpackContextKeys() {
  732. return Object.keys(map);
  733. };
  734. webpackContext.resolve = webpackContextResolve;
  735. webpackContext.id = ${JSON.stringify(id)};
  736. module.exports = webpackContext;`;
  737. }
  738. /**
  739. * @param {Dependency[]} dependencies dependencies
  740. * @param {ModuleId} id module id
  741. * @param {object} context context
  742. * @param {ChunkGraph} context.chunkGraph the chunk graph
  743. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  744. * @returns {string} source code
  745. */
  746. getAsyncWeakSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
  747. const arrow = runtimeTemplate.supportsArrowFunction();
  748. const map = this.getUserRequestMap(dependencies, chunkGraph);
  749. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  750. const returnModuleObject = this.getReturnModuleObjectSource(fakeMap, true);
  751. return `var map = ${JSON.stringify(map, null, "\t")};
  752. ${this.getFakeMapInitStatement(fakeMap)}
  753. function webpackAsyncContext(req) {
  754. return webpackAsyncContextResolve(req).then(${
  755. arrow ? "id =>" : "function(id)"
  756. } {
  757. if(!${RuntimeGlobals.moduleFactories}[id]) {
  758. var e = new Error("Module '" + req + "' ('" + id + "') is not available (weak dependency)");
  759. e.code = 'MODULE_NOT_FOUND';
  760. throw e;
  761. }
  762. ${returnModuleObject}
  763. });
  764. }
  765. function webpackAsyncContextResolve(req) {
  766. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  767. // uncaught exception popping up in devtools
  768. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  769. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  770. var e = new Error("Cannot find module '" + req + "'");
  771. e.code = 'MODULE_NOT_FOUND';
  772. throw e;
  773. }
  774. return map[req];
  775. });
  776. }
  777. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  778. "Object.keys(map)"
  779. )};
  780. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  781. webpackAsyncContext.id = ${JSON.stringify(id)};
  782. module.exports = webpackAsyncContext;`;
  783. }
  784. /**
  785. * @param {Dependency[]} dependencies dependencies
  786. * @param {ModuleId} id module id
  787. * @param {object} context context
  788. * @param {ChunkGraph} context.chunkGraph the chunk graph
  789. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  790. * @returns {string} source code
  791. */
  792. getEagerSource(dependencies, id, { chunkGraph, runtimeTemplate }) {
  793. const arrow = runtimeTemplate.supportsArrowFunction();
  794. const map = this.getUserRequestMap(dependencies, chunkGraph);
  795. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  796. const thenFunction =
  797. fakeMap !== 9
  798. ? `${arrow ? "id =>" : "function(id)"} {
  799. ${this.getReturnModuleObjectSource(fakeMap, true)}
  800. }`
  801. : RuntimeGlobals.require;
  802. return `var map = ${JSON.stringify(map, null, "\t")};
  803. ${this.getFakeMapInitStatement(fakeMap)}
  804. function webpackAsyncContext(req) {
  805. return webpackAsyncContextResolve(req).then(${thenFunction});
  806. }
  807. function webpackAsyncContextResolve(req) {
  808. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  809. // uncaught exception popping up in devtools
  810. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  811. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  812. var e = new Error("Cannot find module '" + req + "'");
  813. e.code = 'MODULE_NOT_FOUND';
  814. throw e;
  815. }
  816. return map[req];
  817. });
  818. }
  819. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  820. "Object.keys(map)"
  821. )};
  822. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  823. webpackAsyncContext.id = ${JSON.stringify(id)};
  824. module.exports = webpackAsyncContext;`;
  825. }
  826. /**
  827. * @param {AsyncDependenciesBlock} block block
  828. * @param {Dependency[]} dependencies dependencies
  829. * @param {ModuleId} id module id
  830. * @param {object} options options object
  831. * @param {RuntimeTemplate} options.runtimeTemplate the runtime template
  832. * @param {ChunkGraph} options.chunkGraph the chunk graph
  833. * @returns {string} source code
  834. */
  835. getLazyOnceSource(block, dependencies, id, { runtimeTemplate, chunkGraph }) {
  836. const promise = runtimeTemplate.blockPromise({
  837. chunkGraph,
  838. block,
  839. message: "lazy-once context",
  840. runtimeRequirements: new Set()
  841. });
  842. const arrow = runtimeTemplate.supportsArrowFunction();
  843. const map = this.getUserRequestMap(dependencies, chunkGraph);
  844. const fakeMap = this.getFakeMap(dependencies, chunkGraph);
  845. const thenFunction =
  846. fakeMap !== 9
  847. ? `${arrow ? "id =>" : "function(id)"} {
  848. ${this.getReturnModuleObjectSource(fakeMap, true)};
  849. }`
  850. : RuntimeGlobals.require;
  851. return `var map = ${JSON.stringify(map, null, "\t")};
  852. ${this.getFakeMapInitStatement(fakeMap)}
  853. function webpackAsyncContext(req) {
  854. return webpackAsyncContextResolve(req).then(${thenFunction});
  855. }
  856. function webpackAsyncContextResolve(req) {
  857. return ${promise}.then(${arrow ? "() =>" : "function()"} {
  858. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  859. var e = new Error("Cannot find module '" + req + "'");
  860. e.code = 'MODULE_NOT_FOUND';
  861. throw e;
  862. }
  863. return map[req];
  864. });
  865. }
  866. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  867. "Object.keys(map)"
  868. )};
  869. webpackAsyncContext.resolve = webpackAsyncContextResolve;
  870. webpackAsyncContext.id = ${JSON.stringify(id)};
  871. module.exports = webpackAsyncContext;`;
  872. }
  873. /**
  874. * @param {AsyncDependenciesBlock[]} blocks blocks
  875. * @param {ModuleId} id module id
  876. * @param {object} context context
  877. * @param {ChunkGraph} context.chunkGraph the chunk graph
  878. * @param {RuntimeTemplate} context.runtimeTemplate the chunk graph
  879. * @returns {string} source code
  880. */
  881. getLazySource(blocks, id, { chunkGraph, runtimeTemplate }) {
  882. const moduleGraph = chunkGraph.moduleGraph;
  883. const arrow = runtimeTemplate.supportsArrowFunction();
  884. let hasMultipleOrNoChunks = false;
  885. let hasNoChunk = true;
  886. const fakeMap = this.getFakeMap(
  887. blocks.map(b => b.dependencies[0]),
  888. chunkGraph
  889. );
  890. const hasFakeMap = typeof fakeMap === "object";
  891. /** @typedef {{userRequest: string, dependency: ContextElementDependency, chunks: undefined | Chunk[], module: Module, block: AsyncDependenciesBlock}} Item */
  892. /**
  893. * @type {Item[]}
  894. */
  895. const items = blocks
  896. .map(block => {
  897. const dependency =
  898. /** @type {ContextElementDependency} */
  899. (block.dependencies[0]);
  900. return {
  901. dependency,
  902. module: /** @type {Module} */ (moduleGraph.getModule(dependency)),
  903. block,
  904. userRequest: dependency.userRequest,
  905. chunks: undefined
  906. };
  907. })
  908. .filter(item => item.module);
  909. for (const item of items) {
  910. const chunkGroup = chunkGraph.getBlockChunkGroup(item.block);
  911. const chunks = (chunkGroup && chunkGroup.chunks) || [];
  912. item.chunks = chunks;
  913. if (chunks.length > 0) {
  914. hasNoChunk = false;
  915. }
  916. if (chunks.length !== 1) {
  917. hasMultipleOrNoChunks = true;
  918. }
  919. }
  920. const shortMode = hasNoChunk && !hasFakeMap;
  921. const sortedItems = items.sort((a, b) => {
  922. if (a.userRequest === b.userRequest) return 0;
  923. return a.userRequest < b.userRequest ? -1 : 1;
  924. });
  925. /** @type {Record<string, ModuleId | (ModuleId[] | ChunkId[])>} */
  926. const map = Object.create(null);
  927. for (const item of sortedItems) {
  928. const moduleId =
  929. /** @type {ModuleId} */
  930. (chunkGraph.getModuleId(item.module));
  931. if (shortMode) {
  932. map[item.userRequest] = moduleId;
  933. } else {
  934. /** @type {(ModuleId | ChunkId)[]} */
  935. const arrayStart = [moduleId];
  936. if (hasFakeMap) {
  937. arrayStart.push(fakeMap[moduleId]);
  938. }
  939. map[item.userRequest] = [
  940. ...arrayStart,
  941. .../** @type {Chunk[]} */
  942. (item.chunks).map(chunk => /** @type {ChunkId} */ (chunk.id))
  943. ];
  944. }
  945. }
  946. const chunksStartPosition = hasFakeMap ? 2 : 1;
  947. const requestPrefix = hasNoChunk
  948. ? "Promise.resolve()"
  949. : hasMultipleOrNoChunks
  950. ? `Promise.all(ids.slice(${chunksStartPosition}).map(${RuntimeGlobals.ensureChunk}))`
  951. : `${RuntimeGlobals.ensureChunk}(ids[${chunksStartPosition}])`;
  952. const returnModuleObject = this.getReturnModuleObjectSource(
  953. fakeMap,
  954. true,
  955. shortMode ? "invalid" : "ids[1]"
  956. );
  957. const webpackAsyncContext =
  958. requestPrefix === "Promise.resolve()"
  959. ? `
  960. function webpackAsyncContext(req) {
  961. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  962. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  963. var e = new Error("Cannot find module '" + req + "'");
  964. e.code = 'MODULE_NOT_FOUND';
  965. throw e;
  966. }
  967. ${shortMode ? "var id = map[req];" : "var ids = map[req], id = ids[0];"}
  968. ${returnModuleObject}
  969. });
  970. }`
  971. : `function webpackAsyncContext(req) {
  972. if(!${RuntimeGlobals.hasOwnProperty}(map, req)) {
  973. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  974. var e = new Error("Cannot find module '" + req + "'");
  975. e.code = 'MODULE_NOT_FOUND';
  976. throw e;
  977. });
  978. }
  979. var ids = map[req], id = ids[0];
  980. return ${requestPrefix}.then(${arrow ? "() =>" : "function()"} {
  981. ${returnModuleObject}
  982. });
  983. }`;
  984. return `var map = ${JSON.stringify(map, null, "\t")};
  985. ${webpackAsyncContext}
  986. webpackAsyncContext.keys = ${runtimeTemplate.returningFunction(
  987. "Object.keys(map)"
  988. )};
  989. webpackAsyncContext.id = ${JSON.stringify(id)};
  990. module.exports = webpackAsyncContext;`;
  991. }
  992. /**
  993. * @param {ModuleId} id module id
  994. * @param {RuntimeTemplate} runtimeTemplate runtime template
  995. * @returns {string} source for empty async context
  996. */
  997. getSourceForEmptyContext(id, runtimeTemplate) {
  998. return `function webpackEmptyContext(req) {
  999. var e = new Error("Cannot find module '" + req + "'");
  1000. e.code = 'MODULE_NOT_FOUND';
  1001. throw e;
  1002. }
  1003. webpackEmptyContext.keys = ${runtimeTemplate.returningFunction("[]")};
  1004. webpackEmptyContext.resolve = webpackEmptyContext;
  1005. webpackEmptyContext.id = ${JSON.stringify(id)};
  1006. module.exports = webpackEmptyContext;`;
  1007. }
  1008. /**
  1009. * @param {ModuleId} id module id
  1010. * @param {RuntimeTemplate} runtimeTemplate runtime template
  1011. * @returns {string} source for empty async context
  1012. */
  1013. getSourceForEmptyAsyncContext(id, runtimeTemplate) {
  1014. const arrow = runtimeTemplate.supportsArrowFunction();
  1015. return `function webpackEmptyAsyncContext(req) {
  1016. // Here Promise.resolve().then() is used instead of new Promise() to prevent
  1017. // uncaught exception popping up in devtools
  1018. return Promise.resolve().then(${arrow ? "() =>" : "function()"} {
  1019. var e = new Error("Cannot find module '" + req + "'");
  1020. e.code = 'MODULE_NOT_FOUND';
  1021. throw e;
  1022. });
  1023. }
  1024. webpackEmptyAsyncContext.keys = ${runtimeTemplate.returningFunction("[]")};
  1025. webpackEmptyAsyncContext.resolve = webpackEmptyAsyncContext;
  1026. webpackEmptyAsyncContext.id = ${JSON.stringify(id)};
  1027. module.exports = webpackEmptyAsyncContext;`;
  1028. }
  1029. /**
  1030. * @param {string} asyncMode module mode
  1031. * @param {CodeGenerationContext} context context info
  1032. * @returns {string} the source code
  1033. */
  1034. getSourceString(asyncMode, { runtimeTemplate, chunkGraph }) {
  1035. const id = /** @type {ModuleId} */ (chunkGraph.getModuleId(this));
  1036. if (asyncMode === "lazy") {
  1037. if (this.blocks && this.blocks.length > 0) {
  1038. return this.getLazySource(this.blocks, id, {
  1039. runtimeTemplate,
  1040. chunkGraph
  1041. });
  1042. }
  1043. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1044. }
  1045. if (asyncMode === "eager") {
  1046. if (this.dependencies && this.dependencies.length > 0) {
  1047. return this.getEagerSource(this.dependencies, id, {
  1048. chunkGraph,
  1049. runtimeTemplate
  1050. });
  1051. }
  1052. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1053. }
  1054. if (asyncMode === "lazy-once") {
  1055. const block = this.blocks[0];
  1056. if (block) {
  1057. return this.getLazyOnceSource(block, block.dependencies, id, {
  1058. runtimeTemplate,
  1059. chunkGraph
  1060. });
  1061. }
  1062. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1063. }
  1064. if (asyncMode === "async-weak") {
  1065. if (this.dependencies && this.dependencies.length > 0) {
  1066. return this.getAsyncWeakSource(this.dependencies, id, {
  1067. chunkGraph,
  1068. runtimeTemplate
  1069. });
  1070. }
  1071. return this.getSourceForEmptyAsyncContext(id, runtimeTemplate);
  1072. }
  1073. if (
  1074. asyncMode === "weak" &&
  1075. this.dependencies &&
  1076. this.dependencies.length > 0
  1077. ) {
  1078. return this.getWeakSyncSource(this.dependencies, id, chunkGraph);
  1079. }
  1080. if (this.dependencies && this.dependencies.length > 0) {
  1081. return this.getSyncSource(this.dependencies, id, chunkGraph);
  1082. }
  1083. return this.getSourceForEmptyContext(id, runtimeTemplate);
  1084. }
  1085. /**
  1086. * @param {string} sourceString source content
  1087. * @param {Compilation=} compilation the compilation
  1088. * @returns {Source} generated source
  1089. */
  1090. getSource(sourceString, compilation) {
  1091. if (this.useSourceMap || this.useSimpleSourceMap) {
  1092. return new OriginalSource(
  1093. sourceString,
  1094. `webpack://${makePathsRelative(
  1095. (compilation && compilation.compiler.context) || "",
  1096. this.identifier(),
  1097. compilation && compilation.compiler.root
  1098. )}`
  1099. );
  1100. }
  1101. return new RawSource(sourceString);
  1102. }
  1103. /**
  1104. * @param {CodeGenerationContext} context context for code generation
  1105. * @returns {CodeGenerationResult} result
  1106. */
  1107. codeGeneration(context) {
  1108. const { chunkGraph, compilation } = context;
  1109. const sources = new Map();
  1110. sources.set(
  1111. "javascript",
  1112. this.getSource(
  1113. this.getSourceString(this.options.mode, context),
  1114. compilation
  1115. )
  1116. );
  1117. const set = new Set();
  1118. const allDeps =
  1119. this.dependencies.length > 0
  1120. ? /** @type {ContextElementDependency[]} */ [...this.dependencies]
  1121. : [];
  1122. for (const block of this.blocks) {
  1123. for (const dep of block.dependencies) {
  1124. allDeps.push(/** @type {ContextElementDependency} */ (dep));
  1125. }
  1126. }
  1127. set.add(RuntimeGlobals.module);
  1128. set.add(RuntimeGlobals.hasOwnProperty);
  1129. if (allDeps.length > 0) {
  1130. const asyncMode = this.options.mode;
  1131. set.add(RuntimeGlobals.require);
  1132. if (asyncMode === "weak") {
  1133. set.add(RuntimeGlobals.moduleFactories);
  1134. } else if (asyncMode === "async-weak") {
  1135. set.add(RuntimeGlobals.moduleFactories);
  1136. set.add(RuntimeGlobals.ensureChunk);
  1137. } else if (asyncMode === "lazy" || asyncMode === "lazy-once") {
  1138. set.add(RuntimeGlobals.ensureChunk);
  1139. }
  1140. if (this.getFakeMap(allDeps, chunkGraph) !== 9) {
  1141. set.add(RuntimeGlobals.createFakeNamespaceObject);
  1142. }
  1143. }
  1144. return {
  1145. sources,
  1146. runtimeRequirements: set
  1147. };
  1148. }
  1149. /**
  1150. * @param {string=} type the source type for which the size should be estimated
  1151. * @returns {number} the estimated size of the module (must be non-zero)
  1152. */
  1153. size(type) {
  1154. // base penalty
  1155. let size = 160;
  1156. // if we don't have dependencies we stop here.
  1157. for (const dependency of this.dependencies) {
  1158. const element = /** @type {ContextElementDependency} */ (dependency);
  1159. size += 5 + element.userRequest.length;
  1160. }
  1161. return size;
  1162. }
  1163. /**
  1164. * @param {ObjectSerializerContext} context context
  1165. */
  1166. serialize(context) {
  1167. const { write } = context;
  1168. write(this._identifier);
  1169. write(this._forceBuild);
  1170. super.serialize(context);
  1171. }
  1172. /**
  1173. * @param {ObjectDeserializerContext} context context
  1174. */
  1175. deserialize(context) {
  1176. const { read } = context;
  1177. this._identifier = read();
  1178. this._forceBuild = read();
  1179. super.deserialize(context);
  1180. }
  1181. }
  1182. makeSerializable(ContextModule, "webpack/lib/ContextModule");
  1183. module.exports = ContextModule;