ContextModule.js 35 KB

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