重构xuchang-screen,从umi->cra, 计划引入redux
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

webpack.config.js 30 KiB

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