webpack.config.js 30 KB

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