webpack.config.js 30 KB

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