WebpackOptionsApply.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. ).apply(compiler);
  357. new DefaultStatsFactoryPlugin().apply(compiler);
  358. new DefaultStatsPresetPlugin().apply(compiler);
  359. new DefaultStatsPrinterPlugin().apply(compiler);
  360. new JavascriptMetaInfoPlugin().apply(compiler);
  361. if (typeof options.mode !== "string") {
  362. const WarnNoModeSetPlugin = require("./WarnNoModeSetPlugin");
  363. new WarnNoModeSetPlugin().apply(compiler);
  364. }
  365. const EnsureChunkConditionsPlugin = require("./optimize/EnsureChunkConditionsPlugin");
  366. new EnsureChunkConditionsPlugin().apply(compiler);
  367. if (options.optimization.removeAvailableModules) {
  368. const RemoveParentModulesPlugin = require("./optimize/RemoveParentModulesPlugin");
  369. new RemoveParentModulesPlugin().apply(compiler);
  370. }
  371. if (options.optimization.removeEmptyChunks) {
  372. const RemoveEmptyChunksPlugin = require("./optimize/RemoveEmptyChunksPlugin");
  373. new RemoveEmptyChunksPlugin().apply(compiler);
  374. }
  375. if (options.optimization.mergeDuplicateChunks) {
  376. const MergeDuplicateChunksPlugin = require("./optimize/MergeDuplicateChunksPlugin");
  377. new MergeDuplicateChunksPlugin().apply(compiler);
  378. }
  379. if (options.optimization.flagIncludedChunks) {
  380. const FlagIncludedChunksPlugin = require("./optimize/FlagIncludedChunksPlugin");
  381. new FlagIncludedChunksPlugin().apply(compiler);
  382. }
  383. if (options.optimization.sideEffects) {
  384. const SideEffectsFlagPlugin = require("./optimize/SideEffectsFlagPlugin");
  385. new SideEffectsFlagPlugin(
  386. options.optimization.sideEffects === true
  387. ).apply(compiler);
  388. }
  389. if (options.optimization.providedExports) {
  390. const FlagDependencyExportsPlugin = require("./FlagDependencyExportsPlugin");
  391. new FlagDependencyExportsPlugin().apply(compiler);
  392. }
  393. if (options.optimization.usedExports) {
  394. const FlagDependencyUsagePlugin = require("./FlagDependencyUsagePlugin");
  395. new FlagDependencyUsagePlugin(
  396. options.optimization.usedExports === "global"
  397. ).apply(compiler);
  398. }
  399. if (options.optimization.innerGraph) {
  400. const InnerGraphPlugin = require("./optimize/InnerGraphPlugin");
  401. new InnerGraphPlugin().apply(compiler);
  402. }
  403. if (options.optimization.mangleExports) {
  404. const MangleExportsPlugin = require("./optimize/MangleExportsPlugin");
  405. new MangleExportsPlugin(
  406. options.optimization.mangleExports !== "size"
  407. ).apply(compiler);
  408. }
  409. if (options.optimization.concatenateModules) {
  410. const ModuleConcatenationPlugin = require("./optimize/ModuleConcatenationPlugin");
  411. new ModuleConcatenationPlugin().apply(compiler);
  412. }
  413. if (options.optimization.splitChunks) {
  414. const SplitChunksPlugin = require("./optimize/SplitChunksPlugin");
  415. new SplitChunksPlugin(options.optimization.splitChunks).apply(compiler);
  416. }
  417. if (options.optimization.runtimeChunk) {
  418. const RuntimeChunkPlugin = require("./optimize/RuntimeChunkPlugin");
  419. new RuntimeChunkPlugin(options.optimization.runtimeChunk).apply(compiler);
  420. }
  421. if (!options.optimization.emitOnErrors) {
  422. const NoEmitOnErrorsPlugin = require("./NoEmitOnErrorsPlugin");
  423. new NoEmitOnErrorsPlugin().apply(compiler);
  424. }
  425. if (options.optimization.realContentHash) {
  426. const RealContentHashPlugin = require("./optimize/RealContentHashPlugin");
  427. new RealContentHashPlugin({
  428. hashFunction: options.output.hashFunction,
  429. hashDigest: options.output.hashDigest
  430. }).apply(compiler);
  431. }
  432. if (options.optimization.checkWasmTypes) {
  433. const WasmFinalizeExportsPlugin = require("./wasm-sync/WasmFinalizeExportsPlugin");
  434. new WasmFinalizeExportsPlugin().apply(compiler);
  435. }
  436. const moduleIds = options.optimization.moduleIds;
  437. if (moduleIds) {
  438. switch (moduleIds) {
  439. case "natural": {
  440. const NaturalModuleIdsPlugin = require("./ids/NaturalModuleIdsPlugin");
  441. new NaturalModuleIdsPlugin().apply(compiler);
  442. break;
  443. }
  444. case "named": {
  445. const NamedModuleIdsPlugin = require("./ids/NamedModuleIdsPlugin");
  446. new NamedModuleIdsPlugin().apply(compiler);
  447. break;
  448. }
  449. case "hashed": {
  450. const WarnDeprecatedOptionPlugin = require("./WarnDeprecatedOptionPlugin");
  451. const HashedModuleIdsPlugin = require("./ids/HashedModuleIdsPlugin");
  452. new WarnDeprecatedOptionPlugin(
  453. "optimization.moduleIds",
  454. "hashed",
  455. "deterministic"
  456. ).apply(compiler);
  457. new HashedModuleIdsPlugin({
  458. hashFunction: options.output.hashFunction
  459. }).apply(compiler);
  460. break;
  461. }
  462. case "deterministic": {
  463. const DeterministicModuleIdsPlugin = require("./ids/DeterministicModuleIdsPlugin");
  464. new DeterministicModuleIdsPlugin().apply(compiler);
  465. break;
  466. }
  467. case "size": {
  468. const OccurrenceModuleIdsPlugin = require("./ids/OccurrenceModuleIdsPlugin");
  469. new OccurrenceModuleIdsPlugin({
  470. prioritiseInitial: true
  471. }).apply(compiler);
  472. break;
  473. }
  474. default:
  475. throw new Error(
  476. `webpack bug: moduleIds: ${moduleIds} is not implemented`
  477. );
  478. }
  479. }
  480. const chunkIds = options.optimization.chunkIds;
  481. if (chunkIds) {
  482. switch (chunkIds) {
  483. case "natural": {
  484. const NaturalChunkIdsPlugin = require("./ids/NaturalChunkIdsPlugin");
  485. new NaturalChunkIdsPlugin().apply(compiler);
  486. break;
  487. }
  488. case "named": {
  489. const NamedChunkIdsPlugin = require("./ids/NamedChunkIdsPlugin");
  490. new NamedChunkIdsPlugin().apply(compiler);
  491. break;
  492. }
  493. case "deterministic": {
  494. const DeterministicChunkIdsPlugin = require("./ids/DeterministicChunkIdsPlugin");
  495. new DeterministicChunkIdsPlugin().apply(compiler);
  496. break;
  497. }
  498. case "size": {
  499. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  500. const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
  501. new OccurrenceChunkIdsPlugin({
  502. prioritiseInitial: true
  503. }).apply(compiler);
  504. break;
  505. }
  506. case "total-size": {
  507. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  508. const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
  509. new OccurrenceChunkIdsPlugin({
  510. prioritiseInitial: false
  511. }).apply(compiler);
  512. break;
  513. }
  514. default:
  515. throw new Error(
  516. `webpack bug: chunkIds: ${chunkIds} is not implemented`
  517. );
  518. }
  519. }
  520. if (options.optimization.nodeEnv) {
  521. const DefinePlugin = require("./DefinePlugin");
  522. new DefinePlugin({
  523. "process.env.NODE_ENV": JSON.stringify(options.optimization.nodeEnv)
  524. }).apply(compiler);
  525. }
  526. if (options.optimization.minimize) {
  527. for (const minimizer of options.optimization.minimizer) {
  528. if (typeof minimizer === "function") {
  529. minimizer.call(compiler, compiler);
  530. } else if (minimizer !== "...") {
  531. minimizer.apply(compiler);
  532. }
  533. }
  534. }
  535. if (options.performance) {
  536. const SizeLimitsPlugin = require("./performance/SizeLimitsPlugin");
  537. new SizeLimitsPlugin(options.performance).apply(compiler);
  538. }
  539. new TemplatedPathPlugin().apply(compiler);
  540. new RecordIdsPlugin({
  541. portableIds: options.optimization.portableRecords
  542. }).apply(compiler);
  543. new WarnCaseSensitiveModulesPlugin().apply(compiler);
  544. const AddManagedPathsPlugin = require("./cache/AddManagedPathsPlugin");
  545. new AddManagedPathsPlugin(
  546. options.snapshot.managedPaths,
  547. options.snapshot.immutablePaths
  548. ).apply(compiler);
  549. if (options.cache && typeof options.cache === "object") {
  550. const cacheOptions = options.cache;
  551. switch (cacheOptions.type) {
  552. case "memory": {
  553. if (isFinite(cacheOptions.maxGenerations)) {
  554. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  555. const MemoryWithGcCachePlugin = require("./cache/MemoryWithGcCachePlugin");
  556. new MemoryWithGcCachePlugin({
  557. maxGenerations: cacheOptions.maxGenerations
  558. }).apply(compiler);
  559. } else {
  560. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  561. const MemoryCachePlugin = require("./cache/MemoryCachePlugin");
  562. new MemoryCachePlugin().apply(compiler);
  563. }
  564. if (cacheOptions.cacheUnaffected) {
  565. if (!options.experiments.cacheUnaffected) {
  566. throw new Error(
  567. "'cache.cacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled"
  568. );
  569. }
  570. compiler.moduleMemCaches = new Map();
  571. }
  572. break;
  573. }
  574. case "filesystem": {
  575. const AddBuildDependenciesPlugin = require("./cache/AddBuildDependenciesPlugin");
  576. for (const key in cacheOptions.buildDependencies) {
  577. const list = cacheOptions.buildDependencies[key];
  578. new AddBuildDependenciesPlugin(list).apply(compiler);
  579. }
  580. if (!isFinite(cacheOptions.maxMemoryGenerations)) {
  581. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  582. const MemoryCachePlugin = require("./cache/MemoryCachePlugin");
  583. new MemoryCachePlugin().apply(compiler);
  584. } else if (cacheOptions.maxMemoryGenerations !== 0) {
  585. //@ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
  586. const MemoryWithGcCachePlugin = require("./cache/MemoryWithGcCachePlugin");
  587. new MemoryWithGcCachePlugin({
  588. maxGenerations: cacheOptions.maxMemoryGenerations
  589. }).apply(compiler);
  590. }
  591. if (cacheOptions.memoryCacheUnaffected) {
  592. if (!options.experiments.cacheUnaffected) {
  593. throw new Error(
  594. "'cache.memoryCacheUnaffected: true' is only allowed when 'experiments.cacheUnaffected' is enabled"
  595. );
  596. }
  597. compiler.moduleMemCaches = new Map();
  598. }
  599. switch (cacheOptions.store) {
  600. case "pack": {
  601. const IdleFileCachePlugin = require("./cache/IdleFileCachePlugin");
  602. const PackFileCacheStrategy = require("./cache/PackFileCacheStrategy");
  603. new IdleFileCachePlugin(
  604. new PackFileCacheStrategy({
  605. compiler,
  606. fs: compiler.intermediateFileSystem,
  607. context: options.context,
  608. cacheLocation: cacheOptions.cacheLocation,
  609. version: cacheOptions.version,
  610. logger: compiler.getInfrastructureLogger(
  611. "webpack.cache.PackFileCacheStrategy"
  612. ),
  613. snapshot: options.snapshot,
  614. maxAge: cacheOptions.maxAge,
  615. profile: cacheOptions.profile,
  616. allowCollectingMemory: cacheOptions.allowCollectingMemory,
  617. compression: cacheOptions.compression
  618. }),
  619. cacheOptions.idleTimeout,
  620. cacheOptions.idleTimeoutForInitialStore,
  621. cacheOptions.idleTimeoutAfterLargeChanges
  622. ).apply(compiler);
  623. break;
  624. }
  625. default:
  626. throw new Error("Unhandled value for cache.store");
  627. }
  628. break;
  629. }
  630. default:
  631. // @ts-expect-error Property 'type' does not exist on type 'never'. ts(2339)
  632. throw new Error(`Unknown cache type ${cacheOptions.type}`);
  633. }
  634. }
  635. new ResolverCachePlugin().apply(compiler);
  636. if (options.ignoreWarnings && options.ignoreWarnings.length > 0) {
  637. const IgnoreWarningsPlugin = require("./IgnoreWarningsPlugin");
  638. new IgnoreWarningsPlugin(options.ignoreWarnings).apply(compiler);
  639. }
  640. compiler.hooks.afterPlugins.call(compiler);
  641. if (!compiler.inputFileSystem) {
  642. throw new Error("No input filesystem provided");
  643. }
  644. compiler.resolverFactory.hooks.resolveOptions
  645. .for("normal")
  646. .tap("WebpackOptionsApply", resolveOptions => {
  647. resolveOptions = cleverMerge(options.resolve, resolveOptions);
  648. resolveOptions.fileSystem = compiler.inputFileSystem;
  649. return resolveOptions;
  650. });
  651. compiler.resolverFactory.hooks.resolveOptions
  652. .for("context")
  653. .tap("WebpackOptionsApply", resolveOptions => {
  654. resolveOptions = cleverMerge(options.resolve, resolveOptions);
  655. resolveOptions.fileSystem = compiler.inputFileSystem;
  656. resolveOptions.resolveToContext = true;
  657. return resolveOptions;
  658. });
  659. compiler.resolverFactory.hooks.resolveOptions
  660. .for("loader")
  661. .tap("WebpackOptionsApply", resolveOptions => {
  662. resolveOptions = cleverMerge(options.resolveLoader, resolveOptions);
  663. resolveOptions.fileSystem = compiler.inputFileSystem;
  664. return resolveOptions;
  665. });
  666. compiler.hooks.afterResolvers.call(compiler);
  667. return options;
  668. }
  669. }
  670. module.exports = WebpackOptionsApply;