You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

772 lines
30 KiB

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