defaults.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const fs = require("fs");
  7. const path = require("path");
  8. const {
  9. JAVASCRIPT_MODULE_TYPE_AUTO,
  10. JSON_MODULE_TYPE,
  11. WEBASSEMBLY_MODULE_TYPE_ASYNC,
  12. JAVASCRIPT_MODULE_TYPE_ESM,
  13. JAVASCRIPT_MODULE_TYPE_DYNAMIC,
  14. WEBASSEMBLY_MODULE_TYPE_SYNC
  15. } = require("../ModuleTypeConstants");
  16. const Template = require("../Template");
  17. const { cleverMerge } = require("../util/cleverMerge");
  18. const {
  19. getTargetsProperties,
  20. getTargetProperties,
  21. getDefaultTarget
  22. } = require("./target");
  23. /** @typedef {import("../../declarations/WebpackOptions").CacheOptionsNormalized} CacheOptions */
  24. /** @typedef {import("../../declarations/WebpackOptions").CssExperimentOptions} CssExperimentOptions */
  25. /** @typedef {import("../../declarations/WebpackOptions").EntryDescription} EntryDescription */
  26. /** @typedef {import("../../declarations/WebpackOptions").EntryNormalized} Entry */
  27. /** @typedef {import("../../declarations/WebpackOptions").Experiments} Experiments */
  28. /** @typedef {import("../../declarations/WebpackOptions").ExperimentsNormalized} ExperimentsNormalized */
  29. /** @typedef {import("../../declarations/WebpackOptions").ExternalsPresets} ExternalsPresets */
  30. /** @typedef {import("../../declarations/WebpackOptions").ExternalsType} ExternalsType */
  31. /** @typedef {import("../../declarations/WebpackOptions").InfrastructureLogging} InfrastructureLogging */
  32. /** @typedef {import("../../declarations/WebpackOptions").JavascriptParserOptions} JavascriptParserOptions */
  33. /** @typedef {import("../../declarations/WebpackOptions").Library} Library */
  34. /** @typedef {import("../../declarations/WebpackOptions").LibraryName} LibraryName */
  35. /** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
  36. /** @typedef {import("../../declarations/WebpackOptions").Loader} Loader */
  37. /** @typedef {import("../../declarations/WebpackOptions").Mode} Mode */
  38. /** @typedef {import("../../declarations/WebpackOptions").ModuleOptionsNormalized} ModuleOptions */
  39. /** @typedef {import("../../declarations/WebpackOptions").Node} WebpackNode */
  40. /** @typedef {import("../../declarations/WebpackOptions").Optimization} Optimization */
  41. /** @typedef {import("../../declarations/WebpackOptions").OutputNormalized} Output */
  42. /** @typedef {import("../../declarations/WebpackOptions").Performance} Performance */
  43. /** @typedef {import("../../declarations/WebpackOptions").ResolveOptions} ResolveOptions */
  44. /** @typedef {import("../../declarations/WebpackOptions").RuleSetRules} RuleSetRules */
  45. /** @typedef {import("../../declarations/WebpackOptions").SnapshotOptions} SnapshotOptions */
  46. /** @typedef {import("../../declarations/WebpackOptions").Target} Target */
  47. /** @typedef {import("../../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  48. /** @typedef {import("./target").TargetProperties} TargetProperties */
  49. const NODE_MODULES_REGEXP = /[\\/]node_modules[\\/]/i;
  50. /**
  51. * Sets a constant default value when undefined
  52. * @template T
  53. * @template {keyof T} P
  54. * @param {T} obj an object
  55. * @param {P} prop a property of this object
  56. * @param {T[P]} value a default value of the property
  57. * @returns {void}
  58. */
  59. const D = (obj, prop, value) => {
  60. if (obj[prop] === undefined) {
  61. obj[prop] = value;
  62. }
  63. };
  64. /**
  65. * Sets a dynamic default value when undefined, by calling the factory function
  66. * @template T
  67. * @template {keyof T} P
  68. * @param {T} obj an object
  69. * @param {P} prop a property of this object
  70. * @param {function(): T[P]} factory a default value factory for the property
  71. * @returns {void}
  72. */
  73. const F = (obj, prop, factory) => {
  74. if (obj[prop] === undefined) {
  75. obj[prop] = factory();
  76. }
  77. };
  78. /**
  79. * Sets a dynamic default value when undefined, by calling the factory function.
  80. * factory must return an array or undefined
  81. * When the current value is already an array an contains "..." it's replaced with
  82. * the result of the factory function
  83. * @template T
  84. * @template {keyof T} P
  85. * @param {T} obj an object
  86. * @param {P} prop a property of this object
  87. * @param {function(): T[P]} factory a default value factory for the property
  88. * @returns {void}
  89. */
  90. const A = (obj, prop, factory) => {
  91. const value = obj[prop];
  92. if (value === undefined) {
  93. obj[prop] = factory();
  94. } else if (Array.isArray(value)) {
  95. /** @type {any[]} */
  96. let newArray = undefined;
  97. for (let i = 0; i < value.length; i++) {
  98. const item = value[i];
  99. if (item === "...") {
  100. if (newArray === undefined) {
  101. newArray = value.slice(0, i);
  102. obj[prop] = /** @type {T[P]} */ (/** @type {unknown} */ (newArray));
  103. }
  104. const items = /** @type {any[]} */ (/** @type {unknown} */ (factory()));
  105. if (items !== undefined) {
  106. for (const item of items) {
  107. newArray.push(item);
  108. }
  109. }
  110. } else if (newArray !== undefined) {
  111. newArray.push(item);
  112. }
  113. }
  114. }
  115. };
  116. /**
  117. * @param {WebpackOptions} options options to be modified
  118. * @returns {void}
  119. */
  120. const applyWebpackOptionsBaseDefaults = options => {
  121. F(options, "context", () => process.cwd());
  122. applyInfrastructureLoggingDefaults(options.infrastructureLogging);
  123. };
  124. /**
  125. * @param {WebpackOptions} options options to be modified
  126. * @returns {void}
  127. */
  128. const applyWebpackOptionsDefaults = options => {
  129. F(options, "context", () => process.cwd());
  130. F(options, "target", () => {
  131. return getDefaultTarget(options.context);
  132. });
  133. const { mode, name, target } = options;
  134. let targetProperties =
  135. target === false
  136. ? /** @type {false} */ (false)
  137. : typeof target === "string"
  138. ? getTargetProperties(target, options.context)
  139. : getTargetsProperties(target, options.context);
  140. const development = mode === "development";
  141. const production = mode === "production" || !mode;
  142. if (typeof options.entry !== "function") {
  143. for (const key of Object.keys(options.entry)) {
  144. F(
  145. options.entry[key],
  146. "import",
  147. () => /** @type {[string]} */ (["./src"])
  148. );
  149. }
  150. }
  151. F(options, "devtool", () => (development ? "eval" : false));
  152. D(options, "watch", false);
  153. D(options, "profile", false);
  154. D(options, "parallelism", 100);
  155. D(options, "recordsInputPath", false);
  156. D(options, "recordsOutputPath", false);
  157. applyExperimentsDefaults(options.experiments, {
  158. production,
  159. development,
  160. targetProperties
  161. });
  162. const futureDefaults = options.experiments.futureDefaults;
  163. F(options, "cache", () =>
  164. development ? { type: /** @type {"memory"} */ ("memory") } : false
  165. );
  166. applyCacheDefaults(options.cache, {
  167. name: name || "default",
  168. mode: mode || "production",
  169. development,
  170. cacheUnaffected: options.experiments.cacheUnaffected
  171. });
  172. const cache = !!options.cache;
  173. applySnapshotDefaults(options.snapshot, {
  174. production,
  175. futureDefaults
  176. });
  177. applyModuleDefaults(options.module, {
  178. cache,
  179. syncWebAssembly: options.experiments.syncWebAssembly,
  180. asyncWebAssembly: options.experiments.asyncWebAssembly,
  181. css: options.experiments.css,
  182. futureDefaults,
  183. isNode: targetProperties && targetProperties.node === true
  184. });
  185. applyOutputDefaults(options.output, {
  186. context: options.context,
  187. targetProperties,
  188. isAffectedByBrowserslist:
  189. target === undefined ||
  190. (typeof target === "string" && target.startsWith("browserslist")) ||
  191. (Array.isArray(target) &&
  192. target.some(target => target.startsWith("browserslist"))),
  193. outputModule: options.experiments.outputModule,
  194. development,
  195. entry: options.entry,
  196. module: options.module,
  197. futureDefaults
  198. });
  199. applyExternalsPresetsDefaults(options.externalsPresets, {
  200. targetProperties,
  201. buildHttp: !!options.experiments.buildHttp
  202. });
  203. applyLoaderDefaults(options.loader, { targetProperties });
  204. F(options, "externalsType", () => {
  205. const validExternalTypes = require("../../schemas/WebpackOptions.json")
  206. .definitions.ExternalsType.enum;
  207. return options.output.library &&
  208. validExternalTypes.includes(options.output.library.type)
  209. ? /** @type {ExternalsType} */ (options.output.library.type)
  210. : options.output.module
  211. ? "module"
  212. : "var";
  213. });
  214. applyNodeDefaults(options.node, {
  215. futureDefaults: options.experiments.futureDefaults,
  216. targetProperties
  217. });
  218. F(options, "performance", () =>
  219. production &&
  220. targetProperties &&
  221. (targetProperties.browser || targetProperties.browser === null)
  222. ? {}
  223. : false
  224. );
  225. applyPerformanceDefaults(options.performance, {
  226. production
  227. });
  228. applyOptimizationDefaults(options.optimization, {
  229. development,
  230. production,
  231. css: options.experiments.css,
  232. records: !!(options.recordsInputPath || options.recordsOutputPath)
  233. });
  234. options.resolve = cleverMerge(
  235. getResolveDefaults({
  236. cache,
  237. context: options.context,
  238. targetProperties,
  239. mode: options.mode
  240. }),
  241. options.resolve
  242. );
  243. options.resolveLoader = cleverMerge(
  244. getResolveLoaderDefaults({ cache }),
  245. options.resolveLoader
  246. );
  247. };
  248. /**
  249. * @param {ExperimentsNormalized} experiments options
  250. * @param {Object} options options
  251. * @param {boolean} options.production is production
  252. * @param {boolean} options.development is development mode
  253. * @param {TargetProperties | false} options.targetProperties target properties
  254. * @returns {void}
  255. */
  256. const applyExperimentsDefaults = (
  257. experiments,
  258. { production, development, targetProperties }
  259. ) => {
  260. D(experiments, "futureDefaults", false);
  261. D(experiments, "backCompat", !experiments.futureDefaults);
  262. D(experiments, "topLevelAwait", experiments.futureDefaults);
  263. D(experiments, "syncWebAssembly", false);
  264. D(experiments, "asyncWebAssembly", experiments.futureDefaults);
  265. D(experiments, "outputModule", false);
  266. D(experiments, "layers", false);
  267. D(experiments, "lazyCompilation", undefined);
  268. D(experiments, "buildHttp", undefined);
  269. D(experiments, "cacheUnaffected", experiments.futureDefaults);
  270. F(experiments, "css", () => (experiments.futureDefaults ? {} : undefined));
  271. if (typeof experiments.buildHttp === "object") {
  272. D(experiments.buildHttp, "frozen", production);
  273. D(experiments.buildHttp, "upgrade", false);
  274. }
  275. if (typeof experiments.css === "object") {
  276. D(
  277. experiments.css,
  278. "exportsOnly",
  279. !targetProperties || !targetProperties.document
  280. );
  281. }
  282. };
  283. /**
  284. * @param {CacheOptions} cache options
  285. * @param {Object} options options
  286. * @param {string} options.name name
  287. * @param {string} options.mode mode
  288. * @param {boolean} options.development is development mode
  289. * @param {boolean} options.cacheUnaffected the cacheUnaffected experiment is enabled
  290. * @returns {void}
  291. */
  292. const applyCacheDefaults = (
  293. cache,
  294. { name, mode, development, cacheUnaffected }
  295. ) => {
  296. if (cache === false) return;
  297. switch (cache.type) {
  298. case "filesystem":
  299. F(cache, "name", () => name + "-" + mode);
  300. D(cache, "version", "");
  301. F(cache, "cacheDirectory", () => {
  302. const cwd = process.cwd();
  303. let dir = cwd;
  304. for (;;) {
  305. try {
  306. if (fs.statSync(path.join(dir, "package.json")).isFile()) break;
  307. // eslint-disable-next-line no-empty
  308. } catch (e) {}
  309. const parent = path.dirname(dir);
  310. if (dir === parent) {
  311. dir = undefined;
  312. break;
  313. }
  314. dir = parent;
  315. }
  316. if (!dir) {
  317. return path.resolve(cwd, ".cache/webpack");
  318. } else if (process.versions.pnp === "1") {
  319. return path.resolve(dir, ".pnp/.cache/webpack");
  320. } else if (process.versions.pnp === "3") {
  321. return path.resolve(dir, ".yarn/.cache/webpack");
  322. } else {
  323. return path.resolve(dir, "node_modules/.cache/webpack");
  324. }
  325. });
  326. F(cache, "cacheLocation", () =>
  327. path.resolve(cache.cacheDirectory, cache.name)
  328. );
  329. D(cache, "hashAlgorithm", "md4");
  330. D(cache, "store", "pack");
  331. D(cache, "compression", false);
  332. D(cache, "profile", false);
  333. D(cache, "idleTimeout", 60000);
  334. D(cache, "idleTimeoutForInitialStore", 5000);
  335. D(cache, "idleTimeoutAfterLargeChanges", 1000);
  336. D(cache, "maxMemoryGenerations", development ? 5 : Infinity);
  337. D(cache, "maxAge", 1000 * 60 * 60 * 24 * 60); // 1 month
  338. D(cache, "allowCollectingMemory", development);
  339. D(cache, "memoryCacheUnaffected", development && cacheUnaffected);
  340. D(cache.buildDependencies, "defaultWebpack", [
  341. path.resolve(__dirname, "..") + path.sep
  342. ]);
  343. break;
  344. case "memory":
  345. D(cache, "maxGenerations", Infinity);
  346. D(cache, "cacheUnaffected", development && cacheUnaffected);
  347. break;
  348. }
  349. };
  350. /**
  351. * @param {SnapshotOptions} snapshot options
  352. * @param {Object} options options
  353. * @param {boolean} options.production is production
  354. * @param {boolean} options.futureDefaults is future defaults enabled
  355. * @returns {void}
  356. */
  357. const applySnapshotDefaults = (snapshot, { production, futureDefaults }) => {
  358. if (futureDefaults) {
  359. F(snapshot, "managedPaths", () =>
  360. process.versions.pnp === "3"
  361. ? [
  362. /^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/
  363. ]
  364. : [/^(.+?[\\/]node_modules[\\/])/]
  365. );
  366. F(snapshot, "immutablePaths", () =>
  367. process.versions.pnp === "3"
  368. ? [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/]
  369. : []
  370. );
  371. } else {
  372. A(snapshot, "managedPaths", () => {
  373. if (process.versions.pnp === "3") {
  374. const match =
  375. /^(.+?)[\\/]cache[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
  376. require.resolve("watchpack")
  377. );
  378. if (match) {
  379. return [path.resolve(match[1], "unplugged")];
  380. }
  381. } else {
  382. const match = /^(.+?[\\/]node_modules[\\/])/.exec(
  383. // eslint-disable-next-line node/no-extraneous-require
  384. require.resolve("watchpack")
  385. );
  386. if (match) {
  387. return [match[1]];
  388. }
  389. }
  390. return [];
  391. });
  392. A(snapshot, "immutablePaths", () => {
  393. if (process.versions.pnp === "1") {
  394. const match =
  395. /^(.+?[\\/]v4)[\\/]npm-watchpack-[^\\/]+-[\da-f]{40}[\\/]node_modules[\\/]/.exec(
  396. require.resolve("watchpack")
  397. );
  398. if (match) {
  399. return [match[1]];
  400. }
  401. } else if (process.versions.pnp === "3") {
  402. const match =
  403. /^(.+?)[\\/]watchpack-npm-[^\\/]+\.zip[\\/]node_modules[\\/]/.exec(
  404. require.resolve("watchpack")
  405. );
  406. if (match) {
  407. return [match[1]];
  408. }
  409. }
  410. return [];
  411. });
  412. }
  413. F(snapshot, "resolveBuildDependencies", () => ({
  414. timestamp: true,
  415. hash: true
  416. }));
  417. F(snapshot, "buildDependencies", () => ({ timestamp: true, hash: true }));
  418. F(snapshot, "module", () =>
  419. production ? { timestamp: true, hash: true } : { timestamp: true }
  420. );
  421. F(snapshot, "resolve", () =>
  422. production ? { timestamp: true, hash: true } : { timestamp: true }
  423. );
  424. };
  425. /**
  426. * @param {JavascriptParserOptions} parserOptions parser options
  427. * @param {Object} options options
  428. * @param {boolean} options.futureDefaults is future defaults enabled
  429. * @param {boolean} options.isNode is node target platform
  430. * @returns {void}
  431. */
  432. const applyJavascriptParserOptionsDefaults = (
  433. parserOptions,
  434. { futureDefaults, isNode }
  435. ) => {
  436. D(parserOptions, "unknownContextRequest", ".");
  437. D(parserOptions, "unknownContextRegExp", false);
  438. D(parserOptions, "unknownContextRecursive", true);
  439. D(parserOptions, "unknownContextCritical", true);
  440. D(parserOptions, "exprContextRequest", ".");
  441. D(parserOptions, "exprContextRegExp", false);
  442. D(parserOptions, "exprContextRecursive", true);
  443. D(parserOptions, "exprContextCritical", true);
  444. D(parserOptions, "wrappedContextRegExp", /.*/);
  445. D(parserOptions, "wrappedContextRecursive", true);
  446. D(parserOptions, "wrappedContextCritical", false);
  447. D(parserOptions, "strictThisContextOnImports", false);
  448. D(parserOptions, "importMeta", true);
  449. D(parserOptions, "dynamicImportMode", "lazy");
  450. D(parserOptions, "dynamicImportPrefetch", false);
  451. D(parserOptions, "dynamicImportPreload", false);
  452. D(parserOptions, "createRequire", isNode);
  453. if (futureDefaults) D(parserOptions, "exportsPresence", "error");
  454. };
  455. /**
  456. * @param {ModuleOptions} module options
  457. * @param {Object} options options
  458. * @param {boolean} options.cache is caching enabled
  459. * @param {boolean} options.syncWebAssembly is syncWebAssembly enabled
  460. * @param {boolean} options.asyncWebAssembly is asyncWebAssembly enabled
  461. * @param {CssExperimentOptions|false} options.css is css enabled
  462. * @param {boolean} options.futureDefaults is future defaults enabled
  463. * @param {boolean} options.isNode is node target platform
  464. * @returns {void}
  465. */
  466. const applyModuleDefaults = (
  467. module,
  468. { cache, syncWebAssembly, asyncWebAssembly, css, futureDefaults, isNode }
  469. ) => {
  470. if (cache) {
  471. D(module, "unsafeCache", module => {
  472. const name = module.nameForCondition();
  473. return name && NODE_MODULES_REGEXP.test(name);
  474. });
  475. } else {
  476. D(module, "unsafeCache", false);
  477. }
  478. F(module.parser, "asset", () => ({}));
  479. F(module.parser.asset, "dataUrlCondition", () => ({}));
  480. if (typeof module.parser.asset.dataUrlCondition === "object") {
  481. D(module.parser.asset.dataUrlCondition, "maxSize", 8096);
  482. }
  483. F(module.parser, "javascript", () => ({}));
  484. applyJavascriptParserOptionsDefaults(module.parser.javascript, {
  485. futureDefaults,
  486. isNode
  487. });
  488. A(module, "defaultRules", () => {
  489. const esm = {
  490. type: JAVASCRIPT_MODULE_TYPE_ESM,
  491. resolve: {
  492. byDependency: {
  493. esm: {
  494. fullySpecified: true
  495. }
  496. }
  497. }
  498. };
  499. const commonjs = {
  500. type: JAVASCRIPT_MODULE_TYPE_DYNAMIC
  501. };
  502. /** @type {RuleSetRules} */
  503. const rules = [
  504. {
  505. mimetype: "application/node",
  506. type: JAVASCRIPT_MODULE_TYPE_AUTO
  507. },
  508. {
  509. test: /\.json$/i,
  510. type: JSON_MODULE_TYPE
  511. },
  512. {
  513. mimetype: "application/json",
  514. type: JSON_MODULE_TYPE
  515. },
  516. {
  517. test: /\.mjs$/i,
  518. ...esm
  519. },
  520. {
  521. test: /\.js$/i,
  522. descriptionData: {
  523. type: "module"
  524. },
  525. ...esm
  526. },
  527. {
  528. test: /\.cjs$/i,
  529. ...commonjs
  530. },
  531. {
  532. test: /\.js$/i,
  533. descriptionData: {
  534. type: "commonjs"
  535. },
  536. ...commonjs
  537. },
  538. {
  539. mimetype: {
  540. or: ["text/javascript", "application/javascript"]
  541. },
  542. ...esm
  543. }
  544. ];
  545. if (asyncWebAssembly) {
  546. const wasm = {
  547. type: WEBASSEMBLY_MODULE_TYPE_ASYNC,
  548. rules: [
  549. {
  550. descriptionData: {
  551. type: "module"
  552. },
  553. resolve: {
  554. fullySpecified: true
  555. }
  556. }
  557. ]
  558. };
  559. rules.push({
  560. test: /\.wasm$/i,
  561. ...wasm
  562. });
  563. rules.push({
  564. mimetype: "application/wasm",
  565. ...wasm
  566. });
  567. } else if (syncWebAssembly) {
  568. const wasm = {
  569. type: WEBASSEMBLY_MODULE_TYPE_SYNC,
  570. rules: [
  571. {
  572. descriptionData: {
  573. type: "module"
  574. },
  575. resolve: {
  576. fullySpecified: true
  577. }
  578. }
  579. ]
  580. };
  581. rules.push({
  582. test: /\.wasm$/i,
  583. ...wasm
  584. });
  585. rules.push({
  586. mimetype: "application/wasm",
  587. ...wasm
  588. });
  589. }
  590. if (css) {
  591. const cssRule = {
  592. type: "css",
  593. resolve: {
  594. fullySpecified: true,
  595. preferRelative: true
  596. }
  597. };
  598. const cssModulesRule = {
  599. type: "css/module",
  600. resolve: {
  601. fullySpecified: true
  602. }
  603. };
  604. rules.push({
  605. test: /\.css$/i,
  606. oneOf: [
  607. {
  608. test: /\.module\.css$/i,
  609. ...cssModulesRule
  610. },
  611. {
  612. ...cssRule
  613. }
  614. ]
  615. });
  616. rules.push({
  617. mimetype: "text/css+module",
  618. ...cssModulesRule
  619. });
  620. rules.push({
  621. mimetype: "text/css",
  622. ...cssRule
  623. });
  624. }
  625. rules.push(
  626. {
  627. dependency: "url",
  628. oneOf: [
  629. {
  630. scheme: /^data$/,
  631. type: "asset/inline"
  632. },
  633. {
  634. type: "asset/resource"
  635. }
  636. ]
  637. },
  638. {
  639. assert: { type: "json" },
  640. type: JSON_MODULE_TYPE
  641. }
  642. );
  643. return rules;
  644. });
  645. };
  646. /**
  647. * @param {Output} output options
  648. * @param {Object} options options
  649. * @param {string} options.context context
  650. * @param {TargetProperties | false} options.targetProperties target properties
  651. * @param {boolean} options.isAffectedByBrowserslist is affected by browserslist
  652. * @param {boolean} options.outputModule is outputModule experiment enabled
  653. * @param {boolean} options.development is development mode
  654. * @param {Entry} options.entry entry option
  655. * @param {ModuleOptions} options.module module option
  656. * @param {boolean} options.futureDefaults is future defaults enabled
  657. * @returns {void}
  658. */
  659. const applyOutputDefaults = (
  660. output,
  661. {
  662. context,
  663. targetProperties: tp,
  664. isAffectedByBrowserslist,
  665. outputModule,
  666. development,
  667. entry,
  668. module,
  669. futureDefaults
  670. }
  671. ) => {
  672. /**
  673. * @param {Library=} library the library option
  674. * @returns {string} a readable library name
  675. */
  676. const getLibraryName = library => {
  677. const libraryName =
  678. typeof library === "object" &&
  679. library &&
  680. !Array.isArray(library) &&
  681. "type" in library
  682. ? library.name
  683. : /** @type {LibraryName=} */ (library);
  684. if (Array.isArray(libraryName)) {
  685. return libraryName.join(".");
  686. } else if (typeof libraryName === "object") {
  687. return getLibraryName(libraryName.root);
  688. } else if (typeof libraryName === "string") {
  689. return libraryName;
  690. }
  691. return "";
  692. };
  693. F(output, "uniqueName", () => {
  694. const libraryName = getLibraryName(output.library).replace(
  695. /^\[(\\*[\w:]+\\*)\](\.)|(\.)\[(\\*[\w:]+\\*)\](?=\.|$)|\[(\\*[\w:]+\\*)\]/g,
  696. (m, a, d1, d2, b, c) => {
  697. const content = a || b || c;
  698. return content.startsWith("\\") && content.endsWith("\\")
  699. ? `${d2 || ""}[${content.slice(1, -1)}]${d1 || ""}`
  700. : "";
  701. }
  702. );
  703. if (libraryName) return libraryName;
  704. const pkgPath = path.resolve(context, "package.json");
  705. try {
  706. const packageInfo = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
  707. return packageInfo.name || "";
  708. } catch (e) {
  709. if (e.code !== "ENOENT") {
  710. e.message += `\nwhile determining default 'output.uniqueName' from 'name' in ${pkgPath}`;
  711. throw e;
  712. }
  713. return "";
  714. }
  715. });
  716. F(output, "module", () => !!outputModule);
  717. D(output, "filename", output.module ? "[name].mjs" : "[name].js");
  718. F(output, "iife", () => !output.module);
  719. D(output, "importFunctionName", "import");
  720. D(output, "importMetaName", "import.meta");
  721. F(output, "chunkFilename", () => {
  722. const filename = output.filename;
  723. if (typeof filename !== "function") {
  724. const hasName = filename.includes("[name]");
  725. const hasId = filename.includes("[id]");
  726. const hasChunkHash = filename.includes("[chunkhash]");
  727. const hasContentHash = filename.includes("[contenthash]");
  728. // Anything changing depending on chunk is fine
  729. if (hasChunkHash || hasContentHash || hasName || hasId) return filename;
  730. // Otherwise prefix "[id]." in front of the basename to make it changing
  731. return filename.replace(/(^|\/)([^/]*(?:\?|$))/, "$1[id].$2");
  732. }
  733. return output.module ? "[id].mjs" : "[id].js";
  734. });
  735. F(output, "cssFilename", () => {
  736. const filename = output.filename;
  737. if (typeof filename !== "function") {
  738. return filename.replace(/\.[mc]?js(\?|$)/, ".css$1");
  739. }
  740. return "[id].css";
  741. });
  742. F(output, "cssChunkFilename", () => {
  743. const chunkFilename = output.chunkFilename;
  744. if (typeof chunkFilename !== "function") {
  745. return chunkFilename.replace(/\.[mc]?js(\?|$)/, ".css$1");
  746. }
  747. return "[id].css";
  748. });
  749. D(output, "assetModuleFilename", "[hash][ext][query]");
  750. D(output, "webassemblyModuleFilename", "[hash].module.wasm");
  751. D(output, "compareBeforeEmit", true);
  752. D(output, "charset", true);
  753. F(output, "hotUpdateGlobal", () =>
  754. Template.toIdentifier(
  755. "webpackHotUpdate" + Template.toIdentifier(output.uniqueName)
  756. )
  757. );
  758. F(output, "chunkLoadingGlobal", () =>
  759. Template.toIdentifier(
  760. "webpackChunk" + Template.toIdentifier(output.uniqueName)
  761. )
  762. );
  763. F(output, "globalObject", () => {
  764. if (tp) {
  765. if (tp.global) return "global";
  766. if (tp.globalThis) return "globalThis";
  767. }
  768. return "self";
  769. });
  770. F(output, "chunkFormat", () => {
  771. if (tp) {
  772. const helpMessage = isAffectedByBrowserslist
  773. ? "Make sure that your 'browserslist' includes only platforms that support these features or select an appropriate 'target' to allow selecting a chunk format by default. Alternatively specify the 'output.chunkFormat' directly."
  774. : "Select an appropriate 'target' to allow selecting one by default, or specify the 'output.chunkFormat' directly.";
  775. if (output.module) {
  776. if (tp.dynamicImport) return "module";
  777. if (tp.document) return "array-push";
  778. throw new Error(
  779. "For the selected environment is no default ESM chunk format available:\n" +
  780. "ESM exports can be chosen when 'import()' is available.\n" +
  781. "JSONP Array push can be chosen when 'document' is available.\n" +
  782. helpMessage
  783. );
  784. } else {
  785. if (tp.document) return "array-push";
  786. if (tp.require) return "commonjs";
  787. if (tp.nodeBuiltins) return "commonjs";
  788. if (tp.importScripts) return "array-push";
  789. throw new Error(
  790. "For the selected environment is no default script chunk format available:\n" +
  791. "JSONP Array push can be chosen when 'document' or 'importScripts' is available.\n" +
  792. "CommonJs exports can be chosen when 'require' or node builtins are available.\n" +
  793. helpMessage
  794. );
  795. }
  796. }
  797. throw new Error(
  798. "Chunk format can't be selected by default when no target is specified"
  799. );
  800. });
  801. D(output, "asyncChunks", true);
  802. F(output, "chunkLoading", () => {
  803. if (tp) {
  804. switch (output.chunkFormat) {
  805. case "array-push":
  806. if (tp.document) return "jsonp";
  807. if (tp.importScripts) return "import-scripts";
  808. break;
  809. case "commonjs":
  810. if (tp.require) return "require";
  811. if (tp.nodeBuiltins) return "async-node";
  812. break;
  813. case "module":
  814. if (tp.dynamicImport) return "import";
  815. break;
  816. }
  817. if (
  818. tp.require === null ||
  819. tp.nodeBuiltins === null ||
  820. tp.document === null ||
  821. tp.importScripts === null
  822. ) {
  823. return "universal";
  824. }
  825. }
  826. return false;
  827. });
  828. F(output, "workerChunkLoading", () => {
  829. if (tp) {
  830. switch (output.chunkFormat) {
  831. case "array-push":
  832. if (tp.importScriptsInWorker) return "import-scripts";
  833. break;
  834. case "commonjs":
  835. if (tp.require) return "require";
  836. if (tp.nodeBuiltins) return "async-node";
  837. break;
  838. case "module":
  839. if (tp.dynamicImportInWorker) return "import";
  840. break;
  841. }
  842. if (
  843. tp.require === null ||
  844. tp.nodeBuiltins === null ||
  845. tp.importScriptsInWorker === null
  846. ) {
  847. return "universal";
  848. }
  849. }
  850. return false;
  851. });
  852. F(output, "wasmLoading", () => {
  853. if (tp) {
  854. if (tp.fetchWasm) return "fetch";
  855. if (tp.nodeBuiltins)
  856. return output.module ? "async-node-module" : "async-node";
  857. if (tp.nodeBuiltins === null || tp.fetchWasm === null) {
  858. return "universal";
  859. }
  860. }
  861. return false;
  862. });
  863. F(output, "workerWasmLoading", () => output.wasmLoading);
  864. F(output, "devtoolNamespace", () => output.uniqueName);
  865. if (output.library) {
  866. F(output.library, "type", () => (output.module ? "module" : "var"));
  867. }
  868. F(output, "path", () => path.join(process.cwd(), "dist"));
  869. F(output, "pathinfo", () => development);
  870. D(output, "sourceMapFilename", "[file].map[query]");
  871. D(
  872. output,
  873. "hotUpdateChunkFilename",
  874. `[id].[fullhash].hot-update.${output.module ? "mjs" : "js"}`
  875. );
  876. D(output, "hotUpdateMainFilename", "[runtime].[fullhash].hot-update.json");
  877. D(output, "crossOriginLoading", false);
  878. F(output, "scriptType", () => (output.module ? "module" : false));
  879. D(
  880. output,
  881. "publicPath",
  882. (tp && (tp.document || tp.importScripts)) || output.scriptType === "module"
  883. ? "auto"
  884. : ""
  885. );
  886. D(output, "workerPublicPath", "");
  887. D(output, "chunkLoadTimeout", 120000);
  888. D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4");
  889. D(output, "hashDigest", "hex");
  890. D(output, "hashDigestLength", futureDefaults ? 16 : 20);
  891. D(output, "strictModuleExceptionHandling", false);
  892. const optimistic = v => v || v === undefined;
  893. const conditionallyOptimistic = (v, c) => (v === undefined && c) || v;
  894. F(
  895. output.environment,
  896. "arrowFunction",
  897. () => tp && optimistic(tp.arrowFunction)
  898. );
  899. F(output.environment, "const", () => tp && optimistic(tp.const));
  900. F(
  901. output.environment,
  902. "destructuring",
  903. () => tp && optimistic(tp.destructuring)
  904. );
  905. F(output.environment, "forOf", () => tp && optimistic(tp.forOf));
  906. F(output.environment, "bigIntLiteral", () => tp && tp.bigIntLiteral);
  907. F(output.environment, "dynamicImport", () =>
  908. conditionallyOptimistic(tp && tp.dynamicImport, output.module)
  909. );
  910. F(output.environment, "module", () =>
  911. conditionallyOptimistic(tp && tp.module, output.module)
  912. );
  913. const { trustedTypes } = output;
  914. if (trustedTypes) {
  915. F(
  916. trustedTypes,
  917. "policyName",
  918. () =>
  919. output.uniqueName.replace(/[^a-zA-Z0-9\-#=_/@.%]+/g, "_") || "webpack"
  920. );
  921. }
  922. /**
  923. * @param {function(EntryDescription): void} fn iterator
  924. * @returns {void}
  925. */
  926. const forEachEntry = fn => {
  927. for (const name of Object.keys(entry)) {
  928. fn(entry[name]);
  929. }
  930. };
  931. A(output, "enabledLibraryTypes", () => {
  932. const enabledLibraryTypes = [];
  933. if (output.library) {
  934. enabledLibraryTypes.push(output.library.type);
  935. }
  936. forEachEntry(desc => {
  937. if (desc.library) {
  938. enabledLibraryTypes.push(desc.library.type);
  939. }
  940. });
  941. return enabledLibraryTypes;
  942. });
  943. A(output, "enabledChunkLoadingTypes", () => {
  944. const enabledChunkLoadingTypes = new Set();
  945. if (output.chunkLoading) {
  946. enabledChunkLoadingTypes.add(output.chunkLoading);
  947. }
  948. if (output.workerChunkLoading) {
  949. enabledChunkLoadingTypes.add(output.workerChunkLoading);
  950. }
  951. forEachEntry(desc => {
  952. if (desc.chunkLoading) {
  953. enabledChunkLoadingTypes.add(desc.chunkLoading);
  954. }
  955. });
  956. return Array.from(enabledChunkLoadingTypes);
  957. });
  958. A(output, "enabledWasmLoadingTypes", () => {
  959. const enabledWasmLoadingTypes = new Set();
  960. if (output.wasmLoading) {
  961. enabledWasmLoadingTypes.add(output.wasmLoading);
  962. }
  963. if (output.workerWasmLoading) {
  964. enabledWasmLoadingTypes.add(output.workerWasmLoading);
  965. }
  966. forEachEntry(desc => {
  967. if (desc.wasmLoading) {
  968. enabledWasmLoadingTypes.add(desc.wasmLoading);
  969. }
  970. });
  971. return Array.from(enabledWasmLoadingTypes);
  972. });
  973. };
  974. /**
  975. * @param {ExternalsPresets} externalsPresets options
  976. * @param {Object} options options
  977. * @param {TargetProperties | false} options.targetProperties target properties
  978. * @param {boolean} options.buildHttp buildHttp experiment enabled
  979. * @returns {void}
  980. */
  981. const applyExternalsPresetsDefaults = (
  982. externalsPresets,
  983. { targetProperties, buildHttp }
  984. ) => {
  985. D(
  986. externalsPresets,
  987. "web",
  988. !buildHttp && targetProperties && targetProperties.web
  989. );
  990. D(externalsPresets, "node", targetProperties && targetProperties.node);
  991. D(externalsPresets, "nwjs", targetProperties && targetProperties.nwjs);
  992. D(
  993. externalsPresets,
  994. "electron",
  995. targetProperties && targetProperties.electron
  996. );
  997. D(
  998. externalsPresets,
  999. "electronMain",
  1000. targetProperties &&
  1001. targetProperties.electron &&
  1002. targetProperties.electronMain
  1003. );
  1004. D(
  1005. externalsPresets,
  1006. "electronPreload",
  1007. targetProperties &&
  1008. targetProperties.electron &&
  1009. targetProperties.electronPreload
  1010. );
  1011. D(
  1012. externalsPresets,
  1013. "electronRenderer",
  1014. targetProperties &&
  1015. targetProperties.electron &&
  1016. targetProperties.electronRenderer
  1017. );
  1018. };
  1019. /**
  1020. * @param {Loader} loader options
  1021. * @param {Object} options options
  1022. * @param {TargetProperties | false} options.targetProperties target properties
  1023. * @returns {void}
  1024. */
  1025. const applyLoaderDefaults = (loader, { targetProperties }) => {
  1026. F(loader, "target", () => {
  1027. if (targetProperties) {
  1028. if (targetProperties.electron) {
  1029. if (targetProperties.electronMain) return "electron-main";
  1030. if (targetProperties.electronPreload) return "electron-preload";
  1031. if (targetProperties.electronRenderer) return "electron-renderer";
  1032. return "electron";
  1033. }
  1034. if (targetProperties.nwjs) return "nwjs";
  1035. if (targetProperties.node) return "node";
  1036. if (targetProperties.web) return "web";
  1037. }
  1038. });
  1039. };
  1040. /**
  1041. * @param {WebpackNode} node options
  1042. * @param {Object} options options
  1043. * @param {TargetProperties | false} options.targetProperties target properties
  1044. * @param {boolean} options.futureDefaults is future defaults enabled
  1045. * @returns {void}
  1046. */
  1047. const applyNodeDefaults = (node, { futureDefaults, targetProperties }) => {
  1048. if (node === false) return;
  1049. F(node, "global", () => {
  1050. if (targetProperties && targetProperties.global) return false;
  1051. // TODO webpack 6 should always default to false
  1052. return futureDefaults ? "warn" : true;
  1053. });
  1054. F(node, "__filename", () => {
  1055. if (targetProperties && targetProperties.node) return "eval-only";
  1056. // TODO webpack 6 should always default to false
  1057. return futureDefaults ? "warn-mock" : "mock";
  1058. });
  1059. F(node, "__dirname", () => {
  1060. if (targetProperties && targetProperties.node) return "eval-only";
  1061. // TODO webpack 6 should always default to false
  1062. return futureDefaults ? "warn-mock" : "mock";
  1063. });
  1064. };
  1065. /**
  1066. * @param {Performance} performance options
  1067. * @param {Object} options options
  1068. * @param {boolean} options.production is production
  1069. * @returns {void}
  1070. */
  1071. const applyPerformanceDefaults = (performance, { production }) => {
  1072. if (performance === false) return;
  1073. D(performance, "maxAssetSize", 250000);
  1074. D(performance, "maxEntrypointSize", 250000);
  1075. F(performance, "hints", () => (production ? "warning" : false));
  1076. };
  1077. /**
  1078. * @param {Optimization} optimization options
  1079. * @param {Object} options options
  1080. * @param {boolean} options.production is production
  1081. * @param {boolean} options.development is development
  1082. * @param {CssExperimentOptions|false} options.css is css enabled
  1083. * @param {boolean} options.records using records
  1084. * @returns {void}
  1085. */
  1086. const applyOptimizationDefaults = (
  1087. optimization,
  1088. { production, development, css, records }
  1089. ) => {
  1090. D(optimization, "removeAvailableModules", false);
  1091. D(optimization, "removeEmptyChunks", true);
  1092. D(optimization, "mergeDuplicateChunks", true);
  1093. D(optimization, "flagIncludedChunks", production);
  1094. F(optimization, "moduleIds", () => {
  1095. if (production) return "deterministic";
  1096. if (development) return "named";
  1097. return "natural";
  1098. });
  1099. F(optimization, "chunkIds", () => {
  1100. if (production) return "deterministic";
  1101. if (development) return "named";
  1102. return "natural";
  1103. });
  1104. F(optimization, "sideEffects", () => (production ? true : "flag"));
  1105. D(optimization, "providedExports", true);
  1106. D(optimization, "usedExports", production);
  1107. D(optimization, "innerGraph", production);
  1108. D(optimization, "mangleExports", production);
  1109. D(optimization, "concatenateModules", production);
  1110. D(optimization, "runtimeChunk", false);
  1111. D(optimization, "emitOnErrors", !production);
  1112. D(optimization, "checkWasmTypes", production);
  1113. D(optimization, "mangleWasmImports", false);
  1114. D(optimization, "portableRecords", records);
  1115. D(optimization, "realContentHash", production);
  1116. D(optimization, "minimize", production);
  1117. A(optimization, "minimizer", () => [
  1118. {
  1119. apply: compiler => {
  1120. // Lazy load the Terser plugin
  1121. const TerserPlugin = require("terser-webpack-plugin");
  1122. new TerserPlugin({
  1123. terserOptions: {
  1124. compress: {
  1125. passes: 2
  1126. }
  1127. }
  1128. }).apply(compiler);
  1129. }
  1130. }
  1131. ]);
  1132. F(optimization, "nodeEnv", () => {
  1133. if (production) return "production";
  1134. if (development) return "development";
  1135. return false;
  1136. });
  1137. const { splitChunks } = optimization;
  1138. if (splitChunks) {
  1139. A(splitChunks, "defaultSizeTypes", () =>
  1140. css ? ["javascript", "css", "unknown"] : ["javascript", "unknown"]
  1141. );
  1142. D(splitChunks, "hidePathInfo", production);
  1143. D(splitChunks, "chunks", "async");
  1144. D(splitChunks, "usedExports", optimization.usedExports === true);
  1145. D(splitChunks, "minChunks", 1);
  1146. F(splitChunks, "minSize", () => (production ? 20000 : 10000));
  1147. F(splitChunks, "minRemainingSize", () => (development ? 0 : undefined));
  1148. F(splitChunks, "enforceSizeThreshold", () => (production ? 50000 : 30000));
  1149. F(splitChunks, "maxAsyncRequests", () => (production ? 30 : Infinity));
  1150. F(splitChunks, "maxInitialRequests", () => (production ? 30 : Infinity));
  1151. D(splitChunks, "automaticNameDelimiter", "-");
  1152. const { cacheGroups } = splitChunks;
  1153. F(cacheGroups, "default", () => ({
  1154. idHint: "",
  1155. reuseExistingChunk: true,
  1156. minChunks: 2,
  1157. priority: -20
  1158. }));
  1159. F(cacheGroups, "defaultVendors", () => ({
  1160. idHint: "vendors",
  1161. reuseExistingChunk: true,
  1162. test: NODE_MODULES_REGEXP,
  1163. priority: -10
  1164. }));
  1165. }
  1166. };
  1167. /**
  1168. * @param {Object} options options
  1169. * @param {boolean} options.cache is cache enable
  1170. * @param {string} options.context build context
  1171. * @param {TargetProperties | false} options.targetProperties target properties
  1172. * @param {Mode} options.mode mode
  1173. * @returns {ResolveOptions} resolve options
  1174. */
  1175. const getResolveDefaults = ({ cache, context, targetProperties, mode }) => {
  1176. /** @type {string[]} */
  1177. const conditions = ["webpack"];
  1178. conditions.push(mode === "development" ? "development" : "production");
  1179. if (targetProperties) {
  1180. if (targetProperties.webworker) conditions.push("worker");
  1181. if (targetProperties.node) conditions.push("node");
  1182. if (targetProperties.web) conditions.push("browser");
  1183. if (targetProperties.electron) conditions.push("electron");
  1184. if (targetProperties.nwjs) conditions.push("nwjs");
  1185. }
  1186. const jsExtensions = [".js", ".json", ".wasm"];
  1187. const tp = targetProperties;
  1188. const browserField =
  1189. tp && tp.web && (!tp.node || (tp.electron && tp.electronRenderer));
  1190. /** @type {function(): ResolveOptions} */
  1191. const cjsDeps = () => ({
  1192. aliasFields: browserField ? ["browser"] : [],
  1193. mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
  1194. conditionNames: ["require", "module", "..."],
  1195. extensions: [...jsExtensions]
  1196. });
  1197. /** @type {function(): ResolveOptions} */
  1198. const esmDeps = () => ({
  1199. aliasFields: browserField ? ["browser"] : [],
  1200. mainFields: browserField ? ["browser", "module", "..."] : ["module", "..."],
  1201. conditionNames: ["import", "module", "..."],
  1202. extensions: [...jsExtensions]
  1203. });
  1204. /** @type {ResolveOptions} */
  1205. const resolveOptions = {
  1206. cache,
  1207. modules: ["node_modules"],
  1208. conditionNames: conditions,
  1209. mainFiles: ["index"],
  1210. extensions: [],
  1211. aliasFields: [],
  1212. exportsFields: ["exports"],
  1213. roots: [context],
  1214. mainFields: ["main"],
  1215. byDependency: {
  1216. wasm: esmDeps(),
  1217. esm: esmDeps(),
  1218. loaderImport: esmDeps(),
  1219. url: {
  1220. preferRelative: true
  1221. },
  1222. worker: {
  1223. ...esmDeps(),
  1224. preferRelative: true
  1225. },
  1226. commonjs: cjsDeps(),
  1227. amd: cjsDeps(),
  1228. // for backward-compat: loadModule
  1229. loader: cjsDeps(),
  1230. // for backward-compat: Custom Dependency
  1231. unknown: cjsDeps(),
  1232. // for backward-compat: getResolve without dependencyType
  1233. undefined: cjsDeps()
  1234. }
  1235. };
  1236. return resolveOptions;
  1237. };
  1238. /**
  1239. * @param {Object} options options
  1240. * @param {boolean} options.cache is cache enable
  1241. * @returns {ResolveOptions} resolve options
  1242. */
  1243. const getResolveLoaderDefaults = ({ cache }) => {
  1244. /** @type {ResolveOptions} */
  1245. const resolveOptions = {
  1246. cache,
  1247. conditionNames: ["loader", "require", "node"],
  1248. exportsFields: ["exports"],
  1249. mainFields: ["loader", "main"],
  1250. extensions: [".js"],
  1251. mainFiles: ["index"]
  1252. };
  1253. return resolveOptions;
  1254. };
  1255. /**
  1256. * @param {InfrastructureLogging} infrastructureLogging options
  1257. * @returns {void}
  1258. */
  1259. const applyInfrastructureLoggingDefaults = infrastructureLogging => {
  1260. F(infrastructureLogging, "stream", () => process.stderr);
  1261. const tty =
  1262. /** @type {any} */ (infrastructureLogging.stream).isTTY &&
  1263. process.env.TERM !== "dumb";
  1264. D(infrastructureLogging, "level", "info");
  1265. D(infrastructureLogging, "debug", false);
  1266. D(infrastructureLogging, "colors", tty);
  1267. D(infrastructureLogging, "appendOnly", !tty);
  1268. };
  1269. exports.applyWebpackOptionsBaseDefaults = applyWebpackOptionsBaseDefaults;
  1270. exports.applyWebpackOptionsDefaults = applyWebpackOptionsDefaults;