defaults.js 45 KB

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