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