webpack.config.js 32 KB

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