webpack.config.js 34 KB

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