defaults.js 51 KB

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