WebpackOptionsApply.js 27 KB

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