defaults.js 38 KB

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