webpack.config.js 32 KB

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