WebpackOptionsApply.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. "use strict";
  6. const OptionsApply = require("./OptionsApply");
  7. const AssetModulesPlugin = require("./asset/AssetModulesPlugin");
  8. const JavascriptModulesPlugin = require("./javascript/JavascriptModulesPlugin");
  9. const JsonModulesPlugin = require("./json/JsonModulesPlugin");
  10. const ChunkPrefetchPreloadPlugin = require("./prefetch/ChunkPrefetchPreloadPlugin");
  11. const EntryOptionPlugin = require("./EntryOptionPlugin");
  12. const RecordIdsPlugin = require("./RecordIdsPlugin");
  13. const RuntimePlugin = require("./RuntimePlugin");
  14. const APIPlugin = require("./APIPlugin");
  15. const CompatibilityPlugin = require("./CompatibilityPlugin");
  16. const ConstPlugin = require("./ConstPlugin");
  17. const ExportsInfoApiPlugin = require("./ExportsInfoApiPlugin");
  18. const WebpackIsIncludedPlugin = require("./WebpackIsIncludedPlugin");
  19. const TemplatedPathPlugin = require("./TemplatedPathPlugin");
  20. const UseStrictPlugin = require("./UseStrictPlugin");
  21. const WarnCaseSensitiveModulesPlugin = require("./WarnCaseSensitiveModulesPlugin");
  22. const DataUriPlugin = require("./schemes/DataUriPlugin");
  23. const FileUriPlugin = require("./schemes/FileUriPlugin");
  24. const ResolverCachePlugin = require("./cache/ResolverCachePlugin");
  25. const CommonJsPlugin = require("./dependencies/CommonJsPlugin");
  26. const HarmonyModulesPlugin = require("./dependencies/HarmonyModulesPlugin");
  27. const ImportMetaContextPlugin = require("./dependencies/ImportMetaContextPlugin");
  28. const ImportMetaPlugin = require("./dependencies/ImportMetaPlugin");
  29. const ImportPlugin = require("./dependencies/ImportPlugin");
  30. const LoaderPlugin = require("./dependencies/LoaderPlugin");
  31. const RequireContextPlugin = require("./dependencies/RequireContextPlugin");
  32. const RequireEnsurePlugin = require("./dependencies/RequireEnsurePlugin");
  33. const RequireIncludePlugin = require("./dependencies/RequireIncludePlugin");
  34. const SystemPlugin = require("./dependencies/SystemPlugin");
  35. const URLPlugin = require("./dependencies/URLPlugin");
  36. const WorkerPlugin = require("./dependencies/WorkerPlugin");
  37. const InferAsyncModulesPlugin = require("./async-modules/InferAsyncModulesPlugin");
  38. const JavascriptMetaInfoPlugin = require("./JavascriptMetaInfoPlugin");
  39. const DefaultStatsFactoryPlugin = require("./stats/DefaultStatsFactoryPlugin");
  40. const DefaultStatsPresetPlugin = require("./stats/DefaultStatsPresetPlugin");
  41. const DefaultStatsPrinterPlugin = require("./stats/DefaultStatsPrinterPlugin");
  42. const { cleverMerge } = require("./util/cleverMerge");
  43. /** @typedef {import("../declarations/WebpackOptions").WebpackOptionsNormalized} WebpackOptions */
  44. /** @typedef {import("./Compiler")} Compiler */
  45. class WebpackOptionsApply extends OptionsApply {
  46. constructor() {
  47. super();
  48. }
  49. /**
  50. * @param {WebpackOptions} options options object
  51. * @param {Compiler} compiler compiler object
  52. * @returns {WebpackOptions} options object
  53. */
  54. process(options, compiler) {
  55. compiler.outputPath = options.output.path;
  56. compiler.recordsInputPath = options.recordsInputPath || null;
  57. compiler.recordsOutputPath = options.recordsOutputPath || null;
  58. compiler.name = options.name;
  59. if (options.externals) {
  60. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  61. const ExternalsPlugin = require("./ExternalsPlugin");
  62. new ExternalsPlugin(options.externalsType, options.externals).apply(
  63. compiler
  64. );
  65. }
  66. if (options.externalsPresets.node) {
  67. const NodeTargetPlugin = require("./node/NodeTargetPlugin");
  68. new NodeTargetPlugin().apply(compiler);
  69. }
  70. if (options.externalsPresets.electronMain) {
  71. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  72. const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
  73. new ElectronTargetPlugin("main").apply(compiler);
  74. }
  75. if (options.externalsPresets.electronPreload) {
  76. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  77. const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
  78. new ElectronTargetPlugin("preload").apply(compiler);
  79. }
  80. if (options.externalsPresets.electronRenderer) {
  81. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  82. const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
  83. new ElectronTargetPlugin("renderer").apply(compiler);
  84. }
  85. if (
  86. options.externalsPresets.electron &&
  87. !options.externalsPresets.electronMain &&
  88. !options.externalsPresets.electronPreload &&
  89. !options.externalsPresets.electronRenderer
  90. ) {
  91. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  92. const ElectronTargetPlugin = require("./electron/ElectronTargetPlugin");
  93. new ElectronTargetPlugin().apply(compiler);
  94. }
  95. if (options.externalsPresets.nwjs) {
  96. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  97. const ExternalsPlugin = require("./ExternalsPlugin");
  98. new ExternalsPlugin("node-commonjs", "nw.gui").apply(compiler);
  99. }
  100. if (options.externalsPresets.webAsync) {
  101. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  102. const ExternalsPlugin = require("./ExternalsPlugin");
  103. new ExternalsPlugin(
  104. "import",
  105. options.experiments.css
  106. ? ({ request, dependencyType }, callback) => {
  107. if (dependencyType === "url") {
  108. if (/^(\/\/|https?:\/\/)/.test(request))
  109. return callback(null, `asset ${request}`);
  110. } else if (dependencyType === "css-import") {
  111. if (/^(\/\/|https?:\/\/)/.test(request))
  112. return callback(null, `css-import ${request}`);
  113. } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
  114. if (/^\.css(\?|$)/.test(request))
  115. return callback(null, `css-import ${request}`);
  116. return callback(null, `import ${request}`);
  117. }
  118. callback();
  119. }
  120. : /^(\/\/|https?:\/\/|std:)/
  121. ).apply(compiler);
  122. } else if (options.externalsPresets.web) {
  123. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  124. const ExternalsPlugin = require("./ExternalsPlugin");
  125. new ExternalsPlugin(
  126. "module",
  127. options.experiments.css
  128. ? ({ request, dependencyType }, callback) => {
  129. if (dependencyType === "url") {
  130. if (/^(\/\/|https?:\/\/)/.test(request))
  131. return callback(null, `asset ${request}`);
  132. } else if (dependencyType === "css-import") {
  133. if (/^(\/\/|https?:\/\/)/.test(request))
  134. return callback(null, `css-import ${request}`);
  135. } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
  136. if (/^\.css(\?|$)/.test(request))
  137. return callback(null, `css-import ${request}`);
  138. return callback(null, `module ${request}`);
  139. }
  140. callback();
  141. }
  142. : /^(\/\/|https?:\/\/|std:)/
  143. ).apply(compiler);
  144. } else if (options.externalsPresets.node) {
  145. if (options.experiments.css) {
  146. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  147. const ExternalsPlugin = require("./ExternalsPlugin");
  148. new ExternalsPlugin(
  149. "module",
  150. ({ request, dependencyType }, callback) => {
  151. if (dependencyType === "url") {
  152. if (/^(\/\/|https?:\/\/)/.test(request))
  153. return callback(null, `asset ${request}`);
  154. } else if (dependencyType === "css-import") {
  155. if (/^(\/\/|https?:\/\/)/.test(request))
  156. return callback(null, `css-import ${request}`);
  157. } else if (/^(\/\/|https?:\/\/|std:)/.test(request)) {
  158. if (/^\.css(\?|$)/.test(request))
  159. return callback(null, `css-import ${request}`);
  160. return callback(null, `module ${request}`);
  161. }
  162. callback();
  163. }
  164. ).apply(compiler);
  165. }
  166. }
  167. new ChunkPrefetchPreloadPlugin().apply(compiler);
  168. if (typeof options.output.chunkFormat === "string") {
  169. switch (options.output.chunkFormat) {
  170. case "array-push": {
  171. const ArrayPushCallbackChunkFormatPlugin = require("./javascript/ArrayPushCallbackChunkFormatPlugin");
  172. new ArrayPushCallbackChunkFormatPlugin().apply(compiler);
  173. break;
  174. }
  175. case "commonjs": {
  176. const CommonJsChunkFormatPlugin = require("./javascript/CommonJsChunkFormatPlugin");
  177. new CommonJsChunkFormatPlugin().apply(compiler);
  178. break;
  179. }
  180. case "module": {
  181. const ModuleChunkFormatPlugin = require("./esm/ModuleChunkFormatPlugin");
  182. new ModuleChunkFormatPlugin().apply(compiler);
  183. break;
  184. }
  185. default:
  186. throw new Error(
  187. "Unsupported chunk format '" + options.output.chunkFormat + "'."
  188. );
  189. }
  190. }
  191. if (options.output.enabledChunkLoadingTypes.length > 0) {
  192. for (const type of options.output.enabledChunkLoadingTypes) {
  193. const EnableChunkLoadingPlugin = require("./javascript/EnableChunkLoadingPlugin");
  194. new EnableChunkLoadingPlugin(type).apply(compiler);
  195. }
  196. }
  197. if (options.output.enabledWasmLoadingTypes.length > 0) {
  198. for (const type of options.output.enabledWasmLoadingTypes) {
  199. const EnableWasmLoadingPlugin = require("./wasm/EnableWasmLoadingPlugin");
  200. new EnableWasmLoadingPlugin(type).apply(compiler);
  201. }
  202. }
  203. if (options.output.enabledLibraryTypes.length > 0) {
  204. for (const type of options.output.enabledLibraryTypes) {
  205. const EnableLibraryPlugin = require("./library/EnableLibraryPlugin");
  206. new EnableLibraryPlugin(type).apply(compiler);
  207. }
  208. }
  209. if (options.output.pathinfo) {
  210. const ModuleInfoHeaderPlugin = require("./ModuleInfoHeaderPlugin");
  211. new ModuleInfoHeaderPlugin(options.output.pathinfo !== true).apply(
  212. compiler
  213. );
  214. }
  215. if (options.output.clean) {
  216. const CleanPlugin = require("./CleanPlugin");
  217. new CleanPlugin(
  218. options.output.clean === true ? {} : options.output.clean
  219. ).apply(compiler);
  220. }
  221. if (options.devtool) {
  222. if (options.devtool.includes("source-map")) {
  223. const hidden = options.devtool.includes("hidden");
  224. const inline = options.devtool.includes("inline");
  225. const evalWrapped = options.devtool.includes("eval");
  226. const cheap = options.devtool.includes("cheap");
  227. const moduleMaps = options.devtool.includes("module");
  228. const noSources = options.devtool.includes("nosources");
  229. const Plugin = evalWrapped
  230. ? require("./EvalSourceMapDevToolPlugin")
  231. : require("./SourceMapDevToolPlugin");
  232. new Plugin({
  233. filename: inline ? null : options.output.sourceMapFilename,
  234. moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
  235. fallbackModuleFilenameTemplate:
  236. options.output.devtoolFallbackModuleFilenameTemplate,
  237. append: hidden ? false : undefined,
  238. module: moduleMaps ? true : cheap ? false : true,
  239. columns: cheap ? false : true,
  240. noSources: noSources,
  241. namespace: options.output.devtoolNamespace
  242. }).apply(compiler);
  243. } else if (options.devtool.includes("eval")) {
  244. const EvalDevToolModulePlugin = require("./EvalDevToolModulePlugin");
  245. new EvalDevToolModulePlugin({
  246. moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
  247. namespace: options.output.devtoolNamespace
  248. }).apply(compiler);
  249. }
  250. }
  251. new JavascriptModulesPlugin().apply(compiler);
  252. new JsonModulesPlugin().apply(compiler);
  253. new AssetModulesPlugin().apply(compiler);
  254. if (!options.experiments.outputModule) {
  255. if (options.output.module) {
  256. throw new Error(
  257. "'output.module: true' is only allowed when 'experiments.outputModule' is enabled"
  258. );
  259. }
  260. if (options.output.enabledLibraryTypes.includes("module")) {
  261. throw new Error(
  262. "library type \"module\" is only allowed when 'experiments.outputModule' is enabled"
  263. );
  264. }
  265. if (options.externalsType === "module") {
  266. throw new Error(
  267. "'externalsType: \"module\"' is only allowed when 'experiments.outputModule' is enabled"
  268. );
  269. }
  270. }
  271. if (options.experiments.syncWebAssembly) {
  272. const WebAssemblyModulesPlugin = require("./wasm-sync/WebAssemblyModulesPlugin");
  273. new WebAssemblyModulesPlugin({
  274. mangleImports: options.optimization.mangleWasmImports
  275. }).apply(compiler);
  276. }
  277. if (options.experiments.asyncWebAssembly) {
  278. const AsyncWebAssemblyModulesPlugin = require("./wasm-async/AsyncWebAssemblyModulesPlugin");
  279. new AsyncWebAssemblyModulesPlugin({
  280. mangleImports: options.optimization.mangleWasmImports
  281. }).apply(compiler);
  282. }
  283. if (options.experiments.css) {
  284. const CssModulesPlugin = require("./css/CssModulesPlugin");
  285. new CssModulesPlugin(options.experiments.css).apply(compiler);
  286. }
  287. if (options.experiments.lazyCompilation) {
  288. const LazyCompilationPlugin = require("./hmr/LazyCompilationPlugin");
  289. const lazyOptions =
  290. typeof options.experiments.lazyCompilation === "object"
  291. ? options.experiments.lazyCompilation
  292. : null;
  293. new LazyCompilationPlugin({
  294. backend:
  295. typeof lazyOptions.backend === "function"
  296. ? lazyOptions.backend
  297. : require("./hmr/lazyCompilationBackend")({
  298. ...lazyOptions.backend,
  299. client:
  300. (lazyOptions.backend && lazyOptions.backend.client) ||
  301. require.resolve(
  302. `../hot/lazy-compilation-${
  303. options.externalsPresets.node ? "node" : "web"
  304. }.js`
  305. )
  306. }),
  307. entries: !lazyOptions || lazyOptions.entries !== false,
  308. imports: !lazyOptions || lazyOptions.imports !== false,
  309. test: (lazyOptions && lazyOptions.test) || undefined
  310. }).apply(compiler);
  311. }
  312. if (options.experiments.buildHttp) {
  313. const HttpUriPlugin = require("./schemes/HttpUriPlugin");
  314. const httpOptions = options.experiments.buildHttp;
  315. new HttpUriPlugin(httpOptions).apply(compiler);
  316. }
  317. new EntryOptionPlugin().apply(compiler);
  318. compiler.hooks.entryOption.call(options.context, options.entry);
  319. new RuntimePlugin().apply(compiler);
  320. new InferAsyncModulesPlugin().apply(compiler);
  321. new DataUriPlugin().apply(compiler);
  322. new FileUriPlugin().apply(compiler);
  323. new CompatibilityPlugin().apply(compiler);
  324. new HarmonyModulesPlugin({
  325. topLevelAwait: options.experiments.topLevelAwait
  326. }).apply(compiler);
  327. if (options.amd !== false) {
  328. const AMDPlugin = require("./dependencies/AMDPlugin");
  329. const RequireJsStuffPlugin = require("./RequireJsStuffPlugin");
  330. new AMDPlugin(options.amd || {}).apply(compiler);
  331. new RequireJsStuffPlugin().apply(compiler);
  332. }
  333. new CommonJsPlugin().apply(compiler);
  334. new LoaderPlugin({}).apply(compiler);
  335. if (options.node !== false) {
  336. const NodeStuffPlugin = require("./NodeStuffPlugin");
  337. new NodeStuffPlugin(options.node).apply(compiler);
  338. }
  339. new APIPlugin().apply(compiler);
  340. new ExportsInfoApiPlugin().apply(compiler);
  341. new WebpackIsIncludedPlugin().apply(compiler);
  342. new ConstPlugin().apply(compiler);
  343. new UseStrictPlugin().apply(compiler);
  344. new RequireIncludePlugin().apply(compiler);
  345. new RequireEnsurePlugin().apply(compiler);
  346. new RequireContextPlugin().apply(compiler);
  347. new ImportPlugin().apply(compiler);
  348. new ImportMetaContextPlugin().apply(compiler);
  349. new SystemPlugin().apply(compiler);
  350. new ImportMetaPlugin().apply(compiler);
  351. new URLPlugin().apply(compiler);
  352. new WorkerPlugin(
  353. options.output.workerChunkLoading,
  354. options.output.workerWasmLoading,
  355. options.output.module,
  356. options.output.workerPublicPath
  357. ).apply(compiler);
  358. new DefaultStatsFactoryPlugin().apply(compiler);
  359. new DefaultStatsPresetPlugin().apply(compiler);
  360. new DefaultStatsPrinterPlugin().apply(compiler);
  361. new JavascriptMetaInfoPlugin().apply(compiler);
  362. if (typeof options.mode !== "string") {
  363. const WarnNoModeSetPlugin = require("./WarnNoModeSetPlugin");
  364. new WarnNoModeSetPlugin().apply(compiler);
  365. }
  366. const EnsureChunkConditionsPlugin = require("./optimize/EnsureChunkConditionsPlugin");
  367. new EnsureChunkConditionsPlugin().apply(compiler);
  368. if (options.optimization.removeAvailableModules) {
  369. const RemoveParentModulesPlugin = require("./optimize/RemoveParentModulesPlugin");
  370. new RemoveParentModulesPlugin().apply(compiler);
  371. }
  372. if (options.optimization.removeEmptyChunks) {
  373. const RemoveEmptyChunksPlugin = require("./optimize/RemoveEmptyChunksPlugin");
  374. new RemoveEmptyChunksPlugin().apply(compiler);
  375. }
  376. if (options.optimization.mergeDuplicateChunks) {
  377. const MergeDuplicateChunksPlugin = require("./optimize/MergeDuplicateChunksPlugin");
  378. new MergeDuplicateChunksPlugin().apply(compiler);
  379. }
  380. if (options.optimization.flagIncludedChunks) {
  381. const FlagIncludedChunksPlugin = require("./optimize/FlagIncludedChunksPlugin");
  382. new FlagIncludedChunksPlugin().apply(compiler);
  383. }
  384. if (options.optimization.sideEffects) {
  385. const SideEffectsFlagPlugin = require("./optimize/SideEffectsFlagPlugin");
  386. new SideEffectsFlagPlugin(
  387. options.optimization.sideEffects === true
  388. ).apply(compiler);
  389. }
  390. if (options.optimization.providedExports) {
  391. const FlagDependencyExportsPlugin = require("./FlagDependencyExportsPlugin");
  392. new FlagDependencyExportsPlugin().apply(compiler);
  393. }
  394. if (options.optimization.usedExports) {
  395. const FlagDependencyUsagePlugin = require("./FlagDependencyUsagePlugin");
  396. new FlagDependencyUsagePlugin(
  397. options.optimization.usedExports === "global"
  398. ).apply(compiler);
  399. }
  400. if (options.optimization.innerGraph) {
  401. const InnerGraphPlugin = require("./optimize/InnerGraphPlugin");
  402. new InnerGraphPlugin().apply(compiler);
  403. }
  404. if (options.optimization.mangleExports) {
  405. const MangleExportsPlugin = require("./optimize/MangleExportsPlugin");
  406. new MangleExportsPlugin(
  407. options.optimization.mangleExports !== "size"
  408. ).apply(compiler);
  409. }
  410. if (options.optimization.concatenateModules) {
  411. const ModuleConcatenationPlugin = require("./optimize/ModuleConcatenationPlugin");
  412. new ModuleConcatenationPlugin().apply(compiler);
  413. }
  414. if (options.optimization.splitChunks) {
  415. const SplitChunksPlugin = require("./optimize/SplitChunksPlugin");
  416. new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler);
  417. }
  418. if (options.optimization.runtimeChunk) {
  419. const RuntimeChunkPlugin = require("./optimize/RuntimeChunkPlugin");
  420. new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler);
  421. }
  422. if (!options.optimization.emitOnErrors) {
  423. const NoEmitOnErrorsPlugin = require("./NoEmitOnErrorsPlugin");
  424. new NoEmitOnErrorsPlugin().apply(compiler);
  425. }
  426. if (options.optimization.realContentHash) {
  427. const RealContentHashPlugin = require("./optimize/RealContentHashPlugin");
  428. new RealContentHashPlugin({
  429. hashFunction: options.output.hashFunction,
  430. hashDigest: options.output.hashDigest
  431. }).apply(compiler);
  432. }
  433. if (options.optimization.checkWasmTypes) {
  434. const WasmFinalizeExportsPlugin = require("./wasm-sync/WasmFinalizeExportsPlugin");
  435. new WasmFinalizeExportsPlugin().apply(compiler);
  436. }
  437. const moduleIds = options.optimization.moduleIds;
  438. if (moduleIds) {
  439. switch (moduleIds) {
  440. case "natural": {
  441. const NaturalModuleIdsPlugin = require("./ids/NaturalModuleIdsPlugin");
  442. new NaturalModuleIdsPlugin().apply(compiler);
  443. break;
  444. }
  445. case "named": {
  446. const NamedModuleIdsPlugin = require("./ids/NamedModuleIdsPlugin");
  447. new NamedModuleIdsPlugin().apply(compiler);
  448. break;
  449. }
  450. case "hashed": {
  451. const WarnDeprecatedOptionPlugin = require("./WarnDeprecatedOptionPlugin");
  452. const HashedModuleIdsPlugin = require("./ids/HashedModuleIdsPlugin");
  453. new WarnDeprecatedOptionPlugin(
  454. "optimization.moduleIds",
  455. "hashed",
  456. "deterministic"
  457. ).apply(compiler);
  458. new HashedModuleIdsPlugin({
  459. hashFunction: options.output.hashFunction
  460. }).apply(compiler);
  461. break;
  462. }
  463. case "deterministic": {
  464. const DeterministicModuleIdsPlugin = require("./ids/DeterministicModuleIdsPlugin");
  465. new DeterministicModuleIdsPlugin().apply(compiler);
  466. break;
  467. }
  468. case "size": {
  469. const OccurrenceModuleIdsPlugin = require("./ids/OccurrenceModuleIdsPlugin");
  470. new OccurrenceModuleIdsPlugin({
  471. prioritiseInitial: true
  472. }).apply(compiler);
  473. break;
  474. }
  475. default:
  476. throw new Error(
  477. `webpack bug: moduleIds: ${moduleIds} is not implemented`
  478. );
  479. }
  480. }
  481. const chunkIds = options.optimization.chunkIds;
  482. if (chunkIds) {
  483. switch (chunkIds) {
  484. case "natural": {
  485. const NaturalChunkIdsPlugin = require("./ids/NaturalChunkIdsPlugin");
  486. new NaturalChunkIdsPlugin().apply(compiler);
  487. break;
  488. }
  489. case "named": {
  490. const NamedChunkIdsPlugin = require("./ids/NamedChunkIdsPlugin");
  491. new NamedChunkIdsPlugin().apply(compiler);
  492. break;
  493. }
  494. case "deterministic": {
  495. const DeterministicChunkIdsPlugin = require("./ids/DeterministicChunkIdsPlugin");
  496. new DeterministicChunkIdsPlugin().apply(compiler);
  497. break;
  498. }
  499. case "size": {
  500. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  501. const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
  502. new OccurrenceChunkIdsPlugin({
  503. prioritiseInitial: true
  504. }).apply(compiler);
  505. break;
  506. }
  507. case "total-size": {
  508. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  509. const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
  510. new OccurrenceChunkIdsPlugin({
  511. prioritiseInitial: false
  512. }).apply(compiler);
  513. break;
  514. }
  515. default:
  516. throw new Error(
  517. `webpack bug: chunkIds: ${chunkIds} is not implemented`
  518. );
  519. }
  520. }
  521. if (options.optimization.nodeEnv) {
  522. const DefinePlugin = require("./DefinePlugin");
  523. new DefinePlugin({
  524. "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv)
  525. }).apply(compiler);
  526. }
  527. if (options.optimization.minimize) {
  528. for (const minimizer of options.optimization.minimizer) {
  529. if (typeof minimizer === "function") {
  530. minimizer.call(compiler, compiler);
  531. } else if (minimizer !== "...") {
  532. minimizer.apply(compiler);
  533. }
  534. }
  535. }
  536. if (options.performance) {
  537. const SizeLimitsPlugin = require("./performance/SizeLimitsPlugin");
  538. new SizeLimitsPlugin(options.performance).apply(compiler);
  539. }
  540. new TemplatedPathPlugin().apply(compiler);
  541. new RecordIdsPlugin({
  542. portableIds: options.optimization.portableRecords
  543. }).apply(compiler);
  544. new WarnCaseSensitiveModulesPlugin().apply(compiler);
  545. const AddManagedPathsPlugin = require("./cache/AddManagedPathsPlugin");
  546. new AddManagedPathsPlugin(
  547. options.snapshot.managedPaths,
  548. options.snapshot.immutablePaths
  549. ).apply(compiler);
  550. if (options.cache && typeof options.cache === "object") {
  551. const cacheOptions = options.cache;
  552. switch (cacheOptions.type) {
  553. case "memory": {
  554. if (isFinite(cacheOptions.maxGenerations)) {
  555. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  556. const MemoryWithGcCachePlugin = require("./cache/MemoryWithGcCachePlugin");
  557. new MemoryWithGcCachePlugin({
  558. maxGenerations: cacheOptions.maxGenerations
  559. }).apply(compiler);
  560. } else {
  561. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  562. const MemoryCachePlugin = require("./cache/MemoryCachePlugin");
  563. new MemoryCachePlugin().apply(compiler);
  564. }
  565. if (cacheOptions.cacheUnaffected) {
  566. if (!options.experiments.cacheUnaffected) {
  567. throw new Error(
  568. "'cache.cacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled"
  569. );
  570. }
  571. compiler.moduleMemCaches = new Map();
  572. }
  573. break;
  574. }
  575. case "filesystem": {
  576. const AddBuildDependenciesPlugin = require("./cache/AddBuildDependenciesPlugin");
  577. for (const key in cacheOptions.buildDependencies) {
  578. const list = cacheOptions.buildDependencies[key];
  579. new AddBuildDependenciesPlugin(list).apply(compiler);
  580. }
  581. if (!isFinite(cacheOptions.maxMemoryGenerations)) {
  582. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  583. const MemoryCachePlugin = require("./cache/MemoryCachePlugin");
  584. new MemoryCachePlugin().apply(compiler);
  585. } else if (cacheOptions.maxMemoryGenerations !== 0) {
  586. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  587. const MemoryWithGcCachePlugin = require("./cache/MemoryWithGcCachePlugin");
  588. new MemoryWithGcCachePlugin({
  589. maxGenerations: cacheOptions.maxMemoryGenerations
  590. }).apply(compiler);
  591. }
  592. if (cacheOptions.memoryCacheUnaffected) {
  593. if (!options.experiments.cacheUnaffected) {
  594. throw new Error(
  595. "'cache.memoryCacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled"
  596. );
  597. }
  598. compiler.moduleMemCaches = new Map();
  599. }
  600. switch (cacheOptions.store) {
  601. case "pack": {
  602. const IdleFileCachePlugin = require("./cache/IdleFileCachePlugin");
  603. const PackFileCacheStrategy = require("./cache/PackFileCacheStrategy");
  604. new IdleFileCachePlugin(
  605. new PackFileCacheStrategy({
  606. compiler,
  607. fs: compiler.intermediateFileSystem,
  608. context: options.context,
  609. cacheLocation: cacheOptions.cacheLocation,
  610. version: cacheOptions.version,
  611. logger: compiler.getInfrastructureLogger(
  612. "webpack.cache.PackFileCacheStrategy"
  613. ),
  614. snapshot: options.snapshot,
  615. maxAge: cacheOptions.maxAge,
  616. profile: cacheOptions.profile,
  617. allowCollectingMemory: cacheOptions.allowCollectingMemory,
  618. compression: cacheOptions.compression
  619. }),
  620. cacheOptions.idleTimeout,
  621. cacheOptions.idleTimeoutForInitialStore,
  622. cacheOptions.idleTimeoutAfterLargeChanges
  623. ).apply(compiler);
  624. break;
  625. }
  626. default:
  627. throw new Error("Unhandled value for cache.store");
  628. }
  629. break;
  630. }
  631. default:
  632. // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339)
  633. throw new Error(`Unknown cache type ${cacheOptions.type}`);
  634. }
  635. }
  636. new ResolverCachePlugin().apply(compiler);
  637. if (options.ignoreWarnings && options.ignoreWarnings.length > 0) {
  638. const IgnoreWarningsPlugin = require("./IgnoreWarningsPlugin");
  639. new IgnoreWarningsPlugin(options.ignoreWarnings).apply(compiler);
  640. }
  641. compiler.hooks.afterPlugins.call(compiler);
  642. if (!compiler.inputFileSystem) {
  643. throw new Error("No input filesystem provided");
  644. }
  645. compiler.resolverFactory.hooks.resolveOptions
  646. .for("normal")
  647. .tap("WebpackOptionsApply", resolveOptions => {
  648. resolveOptions = cleverMerge(options.resolve, resolveOptions);
  649. resolveOptions.fileSystem = compiler.inputFileSystem;
  650. return resolveOptions;
  651. });
  652. compiler.resolverFactory.hooks.resolveOptions
  653. .for("context")
  654. .tap("WebpackOptionsApply", resolveOptions => {
  655. resolveOptions = cleverMerge(options.resolve, resolveOptions);
  656. resolveOptions.fileSystem = compiler.inputFileSystem;
  657. resolveOptions.resolveToContext = true;
  658. return resolveOptions;
  659. });
  660. compiler.resolverFactory.hooks.resolveOptions
  661. .for("loader")
  662. .tap("WebpackOptionsApply", resolveOptions => {
  663. resolveOptions = cleverMerge(options.resolveLoader, resolveOptions);
  664. resolveOptions.fileSystem = compiler.inputFileSystem;
  665. return resolveOptions;
  666. });
  667. compiler.hooks.afterResolvers.call(compiler);
  668. return options;
  669. }
  670. }
  671. module.exports = WebpackOptionsApply;