21702: Merge branch 'main' into 21702-keep-web-replace_files
[arvados.git] / services / workbench2 / config / webpack.config.js
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 'use strict';
6
7 // Do this as the first thing so that any code reading it knows the right env.
8 process.env.BABEL_ENV = 'development';
9 process.env.NODE_ENV = 'development';
10
11 const fs = require('fs');
12 const path = require('path');
13 const webpack = require('webpack');
14 const resolve = require('resolve');
15 const HtmlWebpackPlugin = require('html-webpack-plugin');
16 const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
17 const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
18 const TerserPlugin = require('terser-webpack-plugin');
19 const MiniCssExtractPlugin = require('mini-css-extract-plugin');
20 const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
21 const { WebpackManifestPlugin } = require('webpack-manifest-plugin');
22 const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
23 const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
24 const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
25 const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
26 const ESLintPlugin = require('eslint-webpack-plugin');
27 const paths = require('./paths');
28 const modules = require('./modules');
29 const getClientEnvironment = require('./env');
30 const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
31 const ForkTsCheckerWebpackPlugin =
32   process.env.TSC_COMPILE_ON_ERROR === 'true'
33     ? require('react-dev-utils/ForkTsCheckerWarningWebpackPlugin')
34     : require('react-dev-utils/ForkTsCheckerWebpackPlugin');
35 const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
36
37 const createEnvironmentHash = require('./webpack/persistentCache/createEnvironmentHash');
38
39 // Source maps are resource heavy and can cause out of memory issue for large source files.
40 const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
41
42 const reactRefreshRuntimeEntry = require.resolve('react-refresh/runtime');
43 const reactRefreshWebpackPluginRuntimeEntry = require.resolve(
44   '@pmmmwh/react-refresh-webpack-plugin'
45 );
46 const babelRuntimeEntry = require.resolve('babel-preset-react-app');
47 const babelRuntimeEntryHelpers = require.resolve(
48   '@babel/runtime/helpers/esm/assertThisInitialized',
49   { paths: [babelRuntimeEntry] }
50 );
51 const babelRuntimeRegenerator = require.resolve('@babel/runtime/regenerator', {
52   paths: [babelRuntimeEntry],
53 });
54
55 // Some apps do not need the benefits of saving a web request, so not inlining the chunk
56 // makes for a smoother build process.
57 const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
58
59 const emitErrorsAsWarnings = process.env.ESLINT_NO_DEV_ERRORS === 'true';
60 const disableESLintPlugin = process.env.DISABLE_ESLINT_PLUGIN === 'true';
61
62 const imageInlineSizeLimit = parseInt(
63   process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
64 );
65
66 // Check if TypeScript is setup
67 const useTypeScript = fs.existsSync(paths.appTsConfig);
68
69 // Check if Tailwind config exists
70 const useTailwind = fs.existsSync(
71   path.join(paths.appPath, 'tailwind.config.js')
72 );
73
74 // Get the path to the uncompiled service worker (if it exists).
75 const swSrc = paths.swSrc;
76
77 // style files regexes
78 const cssRegex = /\.css$/;
79 const cssModuleRegex = /\.module\.css$/;
80 const sassRegex = /\.(scss|sass)$/;
81 const sassModuleRegex = /\.module\.(scss|sass)$/;
82
83 const hasJsxRuntime = (() => {
84   if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
85     return false;
86   }
87
88   try {
89     require.resolve('react/jsx-runtime');
90     return true;
91   } catch (e) {
92     return false;
93   }
94 })();
95
96 // This is the production and development configuration.
97 // It is focused on developer experience, fast rebuilds, and a minimal bundle.
98 module.exports = function (webpackEnv) {
99   const isEnvTest = webpackEnv === 'test';
100   const isEnvDevelopment = webpackEnv === 'development';
101   const isEnvProduction = webpackEnv === 'production';
102
103   // Variable used for enabling profiling in Production
104   // passed into alias object. Uses a flag if passed into the build command
105   const isEnvProductionProfile =
106     isEnvProduction && process.argv.includes('--profile');
107
108   // We will provide `paths.publicUrlOrPath` to our app
109   // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
110   // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
111   // Get environment variables to inject into our app.
112   const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
113
114   const shouldUseReactRefresh = env.raw.FAST_REFRESH;
115
116   // common function to get style loaders
117   const getStyleLoaders = (cssOptions, preProcessor) => {
118     const loaders = [
119       isEnvDevelopment && require.resolve('style-loader'),
120       isEnvProduction && {
121         loader: MiniCssExtractPlugin.loader,
122         // css is located in `static/css`, use '../../' to locate index.html folder
123         // in production `paths.publicUrlOrPath` can be a relative path
124         options: paths.publicUrlOrPath.startsWith('.')
125           ? { publicPath: '../../' }
126           : {},
127       },
128       {
129         loader: require.resolve('css-loader'),
130         options: cssOptions,
131       },
132       {
133         // Options for PostCSS as we reference these options twice
134         // Adds vendor prefixing based on your specified browser support in
135         // package.json
136         loader: require.resolve('postcss-loader'),
137         options: {
138           postcssOptions: {
139             // Necessary for external CSS imports to work
140             // https://github.com/facebook/create-react-app/issues/2677
141             ident: 'postcss',
142             config: false,
143             plugins: !useTailwind
144               ? [
145                   'postcss-flexbugs-fixes',
146                   [
147                     'postcss-preset-env',
148                     {
149                       autoprefixer: {
150                         flexbox: 'no-2009',
151                       },
152                       stage: 3,
153                     },
154                   ],
155                   // Adds PostCSS Normalize as the reset css with default options,
156                   // so that it honors browserslist config in package.json
157                   // which in turn let's users customize the target behavior as per their needs.
158                   'postcss-normalize',
159                 ]
160               : [
161                   'tailwindcss',
162                   'postcss-flexbugs-fixes',
163                   [
164                     'postcss-preset-env',
165                     {
166                       autoprefixer: {
167                         flexbox: 'no-2009',
168                       },
169                       stage: 3,
170                     },
171                   ],
172                 ],
173           },
174           sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
175         },
176       },
177     ].filter(Boolean);
178     if (preProcessor) {
179       loaders.push(
180         {
181           loader: require.resolve('resolve-url-loader'),
182           options: {
183             sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
184             root: paths.appSrc,
185           },
186         },
187         {
188           loader: require.resolve(preProcessor),
189           options: {
190             sourceMap: true,
191           },
192         }
193       );
194     }
195     return loaders;
196   };
197
198   return {
199     target: ['browserslist'],
200     mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
201     // Stop compilation early in production
202     bail: isEnvProduction,
203     devtool: isEnvProduction
204       ? shouldUseSourceMap
205         ? 'source-map'
206         : false
207       : isEnvDevelopment && 'cheap-module-source-map',
208     // These are the "entry points" to our application.
209     // This means they will be the "root" imports that are included in JS bundle.
210     entry: paths.appIndexJs,
211     output: {
212       // The build folder.
213       path: paths.appBuild,
214       // Add /* filename */ comments to generated require()s in the output.
215       pathinfo: isEnvDevelopment,
216       // There will be one main bundle, and one file per asynchronous chunk.
217       // In development, it does not produce real files.
218       filename: isEnvProduction
219         ? 'static/js/[name].[contenthash:8].js'
220         : isEnvDevelopment && 'static/js/bundle.js',
221       // There are also additional JS chunk files if you use code splitting.
222       chunkFilename: isEnvProduction
223         ? 'static/js/[name].[contenthash:8].chunk.js'
224         : isEnvDevelopment && 'static/js/[name].chunk.js',
225       assetModuleFilename: 'static/media/[name].[hash][ext]',
226       // webpack uses `publicPath` to determine where the app is being served from.
227       // It requires a trailing slash, or the file assets will get an incorrect path.
228       // We inferred the "public path" (such as / or /my-project) from homepage.
229       publicPath: paths.publicUrlOrPath,
230       // Point sourcemap entries to original disk location (format as URL on Windows)
231       devtoolModuleFilenameTemplate: isEnvProduction
232         ? info =>
233             path
234               .relative(paths.appSrc, info.absoluteResourcePath)
235               .replace(/\\/g, '/')
236         : isEnvDevelopment || isEnvTest ?
237           (info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')) : ()=>null,
238     },
239     cache: {
240       type: 'filesystem',
241       version: createEnvironmentHash(env.raw),
242       cacheDirectory: paths.appWebpackCache,
243       store: 'pack',
244       buildDependencies: {
245         defaultWebpack: ['webpack/lib/'],
246         config: [__filename],
247         tsconfig: [paths.appTsConfig, paths.appJsConfig].filter(f =>
248           fs.existsSync(f)
249         ),
250       },
251     },
252     infrastructureLogging: {
253       level: 'none',
254     },
255     optimization: {
256       minimize: isEnvProduction,
257       minimizer: [
258         // This is only used in production mode
259         new TerserPlugin({
260           terserOptions: {
261             parse: {
262               // We want terser to parse ecma 8 code. However, we don't want it
263               // to apply any minification steps that turns valid ecma 5 code
264               // into invalid ecma 5 code. This is why the 'compress' and 'output'
265               // sections only apply transformations that are ecma 5 safe
266               // https://github.com/facebook/create-react-app/pull/4234
267               ecma: 8,
268             },
269             compress: {
270               ecma: 5,
271               warnings: false,
272               // Disabled because of an issue with Uglify breaking seemingly valid code:
273               // https://github.com/facebook/create-react-app/issues/2376
274               // Pending further investigation:
275               // https://github.com/mishoo/UglifyJS2/issues/2011
276               comparisons: false,
277               // Disabled because of an issue with Terser breaking valid code:
278               // https://github.com/facebook/create-react-app/issues/5250
279               // Pending further investigation:
280               // https://github.com/terser-js/terser/issues/120
281               inline: 2,
282             },
283             mangle: {
284               safari10: true,
285             },
286             // Added for profiling in devtools
287             keep_classnames: isEnvProductionProfile,
288             keep_fnames: isEnvProductionProfile,
289             output: {
290               ecma: 5,
291               comments: false,
292               // Turned on because emoji and regex is not minified properly using default
293               // https://github.com/facebook/create-react-app/issues/2488
294               ascii_only: true,
295             },
296           },
297         }),
298         // This is only used in production mode
299         new CssMinimizerPlugin(),
300       ],
301     },
302     resolve: {
303       // This allows you to set a fallback for where webpack should look for modules.
304       // We placed these paths second because we want `node_modules` to "win"
305       // if there are any conflicts. This matches Node resolution mechanism.
306       // https://github.com/facebook/create-react-app/issues/253
307       modules: ['node_modules', paths.appNodeModules].concat(
308         modules.additionalModulePaths || []
309       ),
310       fallback: { "path": require.resolve("path-browserify") },
311       // These are the reasonable defaults supported by the Node ecosystem.
312       // We also include JSX as a common component filename extension to support
313       // some tools, although we do not recommend using it, see:
314       // https://github.com/facebook/create-react-app/issues/290
315       // `web` extension prefixes have been added for better support
316       // for React Native Web.
317       extensions: paths.moduleFileExtensions
318         .map(ext => `.${ext}`)
319         .filter(ext => useTypeScript || !ext.includes('ts')),
320       alias: {
321         // Support React Native Web
322         // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
323         'react-native': 'react-native-web',
324         // Allows for better profiling with ReactDevTools
325         ...(isEnvProductionProfile && {
326           'react-dom$': 'react-dom/profiling',
327           'scheduler/tracing': 'scheduler/tracing-profiling',
328         }),
329         ...(modules.webpackAliases || {}),
330       },
331       plugins: [
332         // Prevents users from importing files from outside of src/ (or node_modules/).
333         // This often causes confusion because we only process files within src/ with babel.
334         // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
335         // please link the files into your node_modules/ and let module-resolution kick in.
336         // Make sure your source files are compiled, as they will not be processed in any way.
337         new ModuleScopePlugin(paths.appSrc, [
338           paths.appPackageJson,
339           reactRefreshRuntimeEntry,
340           reactRefreshWebpackPluginRuntimeEntry,
341           babelRuntimeEntry,
342           babelRuntimeEntryHelpers,
343           babelRuntimeRegenerator,
344         ]),
345       ],
346     },
347     module: {
348       strictExportPresence: true,
349       rules: [
350         // Handle node_modules packages that contain sourcemaps
351         shouldUseSourceMap && {
352           enforce: 'pre',
353           exclude: /@babel(?:\/|\\{1,2})runtime/,
354           test: /\.(js|mjs|jsx|ts|tsx|css)$/,
355           loader: require.resolve('source-map-loader'),
356         },
357         {
358           // "oneOf" will traverse all following loaders until one will
359           // match the requirements. When no loader matches it will fall
360           // back to the "file" loader at the end of the loader list.
361           oneOf: [
362             // TODO: Merge this config once `image/avif` is in the mime-db
363             // https://github.com/jshttp/mime-db
364             {
365               test: [/\.avif$/],
366               type: 'asset',
367               mimetype: 'image/avif',
368               parser: {
369                 dataUrlCondition: {
370                   maxSize: imageInlineSizeLimit,
371                 },
372               },
373             },
374             // "url" loader works like "file" loader except that it embeds assets
375             // smaller than specified limit in bytes as data URLs to avoid requests.
376             // A missing `test` is equivalent to a match.
377             {
378               test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
379               type: 'asset',
380               parser: {
381                 dataUrlCondition: {
382                   maxSize: imageInlineSizeLimit,
383                 },
384               },
385             },
386             {
387               test: /\.svg$/,
388               use: [
389                 {
390                   loader: require.resolve('@svgr/webpack'),
391                   options: {
392                     prettier: false,
393                     svgo: false,
394                     svgoConfig: {
395                       plugins: [{ removeViewBox: false }],
396                     },
397                     titleProp: true,
398                     ref: true,
399                   },
400                 },
401                 {
402                   loader: require.resolve('file-loader'),
403                   options: {
404                     name: 'static/media/[name].[hash].[ext]',
405                   },
406                 },
407               ],
408               issuer: {
409                 and: [/\.(ts|tsx|js|jsx|md|mdx)$/],
410               },
411             },
412             // Process application JS with Babel.
413             // The preset includes JSX, Flow, TypeScript, and some ESnext features.
414             {
415               test: /\.(js|mjs|jsx|ts|tsx)$/,
416               include: paths.appSrc,
417               loader: require.resolve('babel-loader'),
418               options: {
419                 customize: require.resolve(
420                   'babel-preset-react-app/webpack-overrides'
421                 ),
422                 presets: [
423                   [
424                     require.resolve('babel-preset-react-app'),
425                     {
426                       runtime: hasJsxRuntime ? 'automatic' : 'classic',
427                     },
428                   ],
429                 ],
430                 
431                 plugins: [
432                   isEnvDevelopment &&
433                     shouldUseReactRefresh &&
434                     require.resolve('react-refresh/babel'),
435                 ].filter(Boolean),
436                 // This is a feature of `babel-loader` for webpack (not Babel itself).
437                 // It enables caching results in ./node_modules/.cache/babel-loader/
438                 // directory for faster rebuilds.
439                 cacheDirectory: true,
440                 // See #6846 for context on why cacheCompression is disabled
441                 cacheCompression: false,
442                 compact: isEnvProduction,
443               },
444             },
445             // Process any JS outside of the app with Babel.
446             // Unlike the application JS, we only compile the standard ES features.
447             {
448               test: /\.(js|mjs)$/,
449               exclude: /@babel(?:\/|\\{1,2})runtime/,
450               loader: require.resolve('babel-loader'),
451               options: {
452                 babelrc: false,
453                 configFile: false,
454                 compact: false,
455                 presets: [
456                   [
457                     require.resolve('babel-preset-react-app/dependencies'),
458                     { helpers: true },
459                   ],
460                 ],
461                 cacheDirectory: true,
462                 // See #6846 for context on why cacheCompression is disabled
463                 cacheCompression: false,
464                 
465                 // Babel sourcemaps are needed for debugging into node_modules
466                 // code.  Without the options below, debuggers like VSCode
467                 // show incorrect code and set breakpoints on the wrong lines.
468                 sourceMaps: shouldUseSourceMap,
469                 inputSourceMap: shouldUseSourceMap,
470               },
471             },
472             // "postcss" loader applies autoprefixer to our CSS.
473             // "css" loader resolves paths in CSS and adds assets as dependencies.
474             // "style" loader turns CSS into JS modules that inject <style> tags.
475             // In production, we use MiniCSSExtractPlugin to extract that CSS
476             // to a file, but in development "style" loader enables hot editing
477             // of CSS.
478             // By default we support CSS Modules with the extension .module.css
479             {
480               test: cssRegex,
481               exclude: cssModuleRegex,
482               use: getStyleLoaders({
483                 importLoaders: 1,
484                 sourceMap: isEnvProduction
485                   ? shouldUseSourceMap
486                   : isEnvDevelopment,
487                 modules: {
488                   mode: 'icss',
489                 },
490               }),
491               // Don't consider CSS imports dead code even if the
492               // containing package claims to have no side effects.
493               // Remove this when webpack adds a warning or an error for this.
494               // See https://github.com/webpack/webpack/issues/6571
495               sideEffects: true,
496             },
497             // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
498             // using the extension .module.css
499             {
500               test: cssModuleRegex,
501               use: getStyleLoaders({
502                 importLoaders: 1,
503                 sourceMap: isEnvProduction
504                   ? shouldUseSourceMap
505                   : isEnvDevelopment,
506                 modules: {
507                   mode: 'local',
508                   getLocalIdent: getCSSModuleLocalIdent,
509                 },
510               }),
511             },
512             // Opt-in support for SASS (using .scss or .sass extensions).
513             // By default we support SASS Modules with the
514             // extensions .module.scss or .module.sass
515             {
516               test: sassRegex,
517               exclude: sassModuleRegex,
518               use: getStyleLoaders(
519                 {
520                   importLoaders: 3,
521                   sourceMap: isEnvProduction
522                     ? shouldUseSourceMap
523                     : isEnvDevelopment,
524                   modules: {
525                     mode: 'icss',
526                   },
527                 },
528                 'sass-loader'
529               ),
530               // Don't consider CSS imports dead code even if the
531               // containing package claims to have no side effects.
532               // Remove this when webpack adds a warning or an error for this.
533               // See https://github.com/webpack/webpack/issues/6571
534               sideEffects: true,
535             },
536             // Adds support for CSS Modules, but using SASS
537             // using the extension .module.scss or .module.sass
538             {
539               test: sassModuleRegex,
540               use: getStyleLoaders(
541                 {
542                   importLoaders: 3,
543                   sourceMap: isEnvProduction
544                     ? shouldUseSourceMap
545                     : isEnvDevelopment,
546                   modules: {
547                     mode: 'local',
548                     getLocalIdent: getCSSModuleLocalIdent,
549                   },
550                 },
551                 'sass-loader'
552               ),
553             },
554             // "file" loader makes sure those assets get served by WebpackDevServer.
555             // When you `import` an asset, you get its (virtual) filename.
556             // In production, they would get copied to the `build` folder.
557             // This loader doesn't use a "test" so it will catch all modules
558             // that fall through the other loaders.
559             {
560               // Exclude `js` files to keep "css" loader working as it injects
561               // its runtime that would otherwise be processed through "file" loader.
562               // Also exclude `html` and `json` extensions so they get processed
563               // by webpacks internal loaders.
564               exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
565               type: 'asset/resource',
566             },
567             // ** STOP ** Are you adding a new loader?
568             // Make sure to add the new loader(s) before the "file" loader.
569           ],
570         },
571       ].filter(Boolean),
572     },
573     plugins: [
574       // Generates an `index.html` file with the <script> injected.
575       new HtmlWebpackPlugin(
576         Object.assign(
577           {},
578           {
579             inject: true,
580             template: paths.appHtml,
581           },
582           isEnvProduction
583             ? {
584                 minify: {
585                   removeComments: true,
586                   collapseWhitespace: true,
587                   removeRedundantAttributes: true,
588                   useShortDoctype: true,
589                   removeEmptyAttributes: true,
590                   removeStyleLinkTypeAttributes: true,
591                   keepClosingSlash: true,
592                   minifyJS: true,
593                   minifyCSS: true,
594                   minifyURLs: true,
595                 },
596               }
597             : undefined
598         )
599       ),
600       // Inlines the webpack runtime script. This script is too small to warrant
601       // a network request.
602       // https://github.com/facebook/create-react-app/issues/5358
603       isEnvProduction &&
604         shouldInlineRuntimeChunk &&
605         new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
606       // Makes some environment variables available in index.html.
607       // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
608       // <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
609       // It will be an empty string unless you specify "homepage"
610       // in `package.json`, in which case it will be the pathname of that URL.
611       new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
612       // This gives some necessary context to module not found errors, such as
613       // the requesting resource.
614       new ModuleNotFoundPlugin(paths.appPath),
615       // Makes some environment variables available to the JS code, for example:
616       // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
617       // It is absolutely essential that NODE_ENV is set to production
618       // during a production build.
619       // Otherwise React will be compiled in the very slow development mode.
620       new webpack.DefinePlugin(env.stringified),
621       // Experimental hot reloading for React .
622       // https://github.com/facebook/react/tree/main/packages/react-refresh
623       isEnvDevelopment &&
624         shouldUseReactRefresh &&
625         new ReactRefreshWebpackPlugin({
626           overlay: false,
627         }),
628       // Watcher doesn't work well if you mistype casing in a path so we use
629       // a plugin that prints an error when you attempt to do this.
630       // See https://github.com/facebook/create-react-app/issues/240
631       isEnvDevelopment && new CaseSensitivePathsPlugin(),
632       isEnvProduction &&
633         new MiniCssExtractPlugin({
634           // Options similar to the same options in webpackOptions.output
635           // both options are optional
636           filename: 'static/css/[name].[contenthash:8].css',
637           chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
638         }),
639       // Generate an asset manifest file with the following content:
640       // - "files" key: Mapping of all asset filenames to their corresponding
641       //   output file so that tools can pick it up without having to parse
642       //   `index.html`
643       // - "entrypoints" key: Array of files which are included in `index.html`,
644       //   can be used to reconstruct the HTML if necessary
645       new WebpackManifestPlugin({
646         fileName: 'asset-manifest.json',
647         publicPath: paths.publicUrlOrPath,
648         generate: (seed, files, entrypoints) => {
649           const manifestFiles = files.reduce((manifest, file) => {
650             manifest[file.name] = file.path;
651             return manifest;
652           }, seed);
653           const entrypointFiles = entrypoints.main.filter(
654             fileName => !fileName.endsWith('.map')
655           );
656
657           return {
658             files: manifestFiles,
659             entrypoints: entrypointFiles,
660           };
661         },
662       }),
663       // Moment.js is an extremely popular library that bundles large locale files
664       // by default due to how webpack interprets its code. This is a practical
665       // solution that requires the user to opt into importing specific locales.
666       // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
667       // You can remove this if you don't use Moment.js:
668       new webpack.IgnorePlugin({
669         resourceRegExp: /^\.\/locale$/,
670         contextRegExp: /moment$/,
671       }),
672       // Generate a service worker script that will precache, and keep up to date,
673       // the HTML & assets that are part of the webpack build.
674       isEnvProduction &&
675         fs.existsSync(swSrc) &&
676         new WorkboxWebpackPlugin.InjectManifest({
677           swSrc,
678           dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
679           exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
680           // Bump up the default maximum size (2mb) that's precached,
681           // to make lazy-loading failure scenarios less likely.
682           // See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
683           maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
684         }),
685       // TypeScript type checking
686       useTypeScript &&
687         new ForkTsCheckerWebpackPlugin({
688           async: isEnvDevelopment,
689           typescript: {
690             typescriptPath: resolve.sync('typescript', {
691               basedir: paths.appNodeModules,
692             }),
693             configOverwrite: {
694               compilerOptions: {
695                 sourceMap: isEnvProduction
696                   ? shouldUseSourceMap
697                   : isEnvDevelopment,
698                 skipLibCheck: true,
699                 inlineSourceMap: false,
700                 declarationMap: false,
701                 noEmit: true,
702                 incremental: true,
703                 tsBuildInfoFile: paths.appTsBuildInfoFile,
704               },
705             },
706             context: paths.appPath,
707             diagnosticOptions: {
708               syntactic: true,
709             },
710             mode: 'write-references',
711             // profile: true,
712           },
713           issue: {
714             // This one is specifically to match during CI tests,
715             // as micromatch doesn't match
716             // '../cra-template-typescript/template/src/App.tsx'
717             // otherwise.
718             include: [
719               { file: '../**/src/**/*.{ts,tsx}' },
720               { file: '**/src/**/*.{ts,tsx}' },
721             ],
722             exclude: [
723               { file: '**/src/**/__tests__/**' },
724               { file: '**/src/**/?(*.){spec|test}.*' },
725               { file: '**/src/setupProxy.*' },
726               { file: '**/src/setupTests.*' },
727             ],
728           },
729           logger: {
730             infrastructure: 'silent',
731           },
732         }),
733       !disableESLintPlugin &&
734         new ESLintPlugin({
735           // Plugin options
736           extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
737           formatter: require.resolve('react-dev-utils/eslintFormatter'),
738           eslintPath: require.resolve('eslint'),
739           failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
740           context: paths.appSrc,
741           cache: true,
742           cacheLocation: path.resolve(
743             paths.appNodeModules,
744             '.cache/.eslintcache'
745           ),
746           // ESLint class options
747           cwd: paths.appPath,
748           resolvePluginsRelativeTo: __dirname,
749           baseConfig: {
750             extends: [require.resolve('eslint-config-react-app/base')],
751             rules: {
752               ...(!hasJsxRuntime && {
753                 'react/react-in-jsx-scope': 'error',
754               }),
755             },
756             ignorePatterns: ['**/*.cy.js'],
757           },
758         }),
759     ].filter(Boolean),
760     // Turn off performance processing because we utilize
761     // our own hints via the FileSizeReporter
762     performance: false,
763   };
764 };