webpack.config.js 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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 => 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('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. ].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. {
  511. test: lessRegex,
  512. exclude: lessModuleRegex,
  513. use: getStyleLoaders({
  514. importLoaders: 2,
  515. sourceMap: isEnvProduction && shouldUseSourceMap,
  516. },
  517. 'less-loader'
  518. ),
  519. sideEffects: true,
  520. },
  521. {
  522. test: lessModuleRegex,
  523. use: getStyleLoaders({
  524. importLoaders: 2,
  525. modules: true,
  526. getLocalIdent: getCSSModuleLocalIdent,
  527. sourceMap: isEnvProduction && shouldUseSourceMap,
  528. },
  529. 'less-loader'
  530. ),
  531. },
  532. // Adds support for CSS Modules, but using SASS
  533. // using the extension .module.scss or .module.sass
  534. {
  535. test: sassModuleRegex,
  536. use: getStyleLoaders(
  537. {
  538. importLoaders: 3,
  539. sourceMap: isEnvProduction
  540. ? shouldUseSourceMap
  541. : isEnvDevelopment,
  542. modules: {
  543. mode: 'local',
  544. getLocalIdent: getCSSModuleLocalIdent,
  545. },
  546. },
  547. 'sass-loader'
  548. ),
  549. },
  550. {
  551. test: lessRegex,
  552. exclude: lessModuleRegex,
  553. use: getStyleLoaders({
  554. importLoaders: 1,
  555. modules: true,
  556. sourceMap: isEnvProduction && shouldUseSourceMap
  557. },
  558. "less-loader"
  559. ),
  560. sideEffects: true
  561. },
  562. {
  563. test: lessModuleRegex,
  564. use: getStyleLoaders({
  565. importLoaders: 1,
  566. sourceMap: isEnvProduction && shouldUseSourceMap,
  567. modules: true,
  568. getLocalIdent: getCSSModuleLocalIdent
  569. },
  570. "less-loader"
  571. )
  572. },
  573. // "file" loader makes sure those assets get served by WebpackDevServer.
  574. // When you `import` an asset, you get its (virtual) filename.
  575. // In production, they would get copied to the `build` folder.
  576. // This loader doesn't use a "test" so it will catch all modules
  577. // that fall through the other loaders.
  578. {
  579. // Exclude `js` files to keep "css" loader working as it injects
  580. // its runtime that would otherwise be processed through "file" loader.
  581. // Also exclude `html` and `json` extensions so they get processed
  582. // by webpacks internal loaders.
  583. exclude: [/^$/, /\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
  584. type: 'asset/resource',
  585. },
  586. // ** STOP ** Are you adding a new loader?
  587. // Make sure to add the new loader(s) before the "file" loader.
  588. ],
  589. },
  590. ].filter(Boolean),
  591. },
  592. plugins: [
  593. // Generates an `index.html` file with the <script> injected.
  594. new HtmlWebpackPlugin(
  595. Object.assign(
  596. {},
  597. {
  598. inject: true,
  599. template: paths.appHtml,
  600. },
  601. isEnvProduction
  602. ? {
  603. minify: {
  604. removeComments: true,
  605. collapseWhitespace: true,
  606. removeRedundantAttributes: true,
  607. useShortDoctype: true,
  608. removeEmptyAttributes: true,
  609. removeStyleLinkTypeAttributes: true,
  610. keepClosingSlash: true,
  611. minifyJS: true,
  612. minifyCSS: true,
  613. minifyURLs: true,
  614. },
  615. }
  616. : undefined
  617. )
  618. ),
  619. // Inlines the webpack runtime script. This script is too small to warrant
  620. // a network request.
  621. // https://github.com/facebook/create-react-app/issues/5358
  622. isEnvProduction &&
  623. shouldInlineRuntimeChunk &&
  624. new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
  625. // Makes some environment variables available in index.html.
  626. // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  627. // <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
  628. // It will be an empty string unless you specify "homepage"
  629. // in `package.json`, in which case it will be the pathname of that URL.
  630. new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
  631. // This gives some necessary context to module not found errors, such as
  632. // the requesting resource.
  633. new ModuleNotFoundPlugin(paths.appPath),
  634. // Makes some environment variables available to the JS code, for example:
  635. // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  636. // It is absolutely essential that NODE_ENV is set to production
  637. // during a production build.
  638. // Otherwise React will be compiled in the very slow development mode.
  639. new webpack.DefinePlugin(env.stringified),
  640. // Experimental hot reloading for React .
  641. // https://github.com/facebook/react/tree/main/packages/react-refresh
  642. isEnvDevelopment &&
  643. shouldUseReactRefresh &&
  644. new ReactRefreshWebpackPlugin({
  645. overlay: false,
  646. }),
  647. // Watcher doesn't work well if you mistype casing in a path so we use
  648. // a plugin that prints an error when you attempt to do this.
  649. // See https://github.com/facebook/create-react-app/issues/240
  650. isEnvDevelopment && new CaseSensitivePathsPlugin(),
  651. isEnvProduction &&
  652. new MiniCssExtractPlugin({
  653. // Options similar to the same options in webpackOptions.output
  654. // both options are optional
  655. filename: 'static/css/[name].[contenthash:8].css',
  656. chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
  657. }),
  658. // Generate an asset manifest file with the following content:
  659. // - "files" key: Mapping of all asset filenames to their corresponding
  660. // output file so that tools can pick it up without having to parse
  661. // `index.html`
  662. // - "entrypoints" key: Array of files which are included in `index.html`,
  663. // can be used to reconstruct the HTML if necessary
  664. new WebpackManifestPlugin({
  665. fileName: 'asset-manifest.json',
  666. publicPath: paths.publicUrlOrPath,
  667. generate: (seed, files, entrypoints) => {
  668. const manifestFiles = files.reduce((manifest, file) => {
  669. manifest[file.name] = file.path;
  670. return manifest;
  671. }, seed);
  672. const entrypointFiles = entrypoints.main.filter(
  673. fileName => !fileName.endsWith('.map')
  674. );
  675. return {
  676. files: manifestFiles,
  677. entrypoints: entrypointFiles,
  678. };
  679. },
  680. }),
  681. // Moment.js is an extremely popular library that bundles large locale files
  682. // by default due to how webpack interprets its code. This is a practical
  683. // solution that requires the user to opt into importing specific locales.
  684. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  685. // You can remove this if you don't use Moment.js:
  686. new webpack.IgnorePlugin({
  687. resourceRegExp: /^\.\/locale$/,
  688. contextRegExp: /moment$/,
  689. }),
  690. // Generate a service worker script that will precache, and keep up to date,
  691. // the HTML & assets that are part of the webpack build.
  692. isEnvProduction &&
  693. fs.existsSync(swSrc) &&
  694. new WorkboxWebpackPlugin.InjectManifest({
  695. swSrc,
  696. dontCacheBustURLsMatching: /\.[0-9a-f]{8}\./,
  697. exclude: [/\.map$/, /asset-manifest\.json$/, /LICENSE/],
  698. // Bump up the default maximum size (2mb) that's precached,
  699. // to make lazy-loading failure scenarios less likely.
  700. // See https://github.com/cra-template/pwa/issues/13#issuecomment-722667270
  701. maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
  702. }),
  703. // TypeScript type checking
  704. useTypeScript &&
  705. new ForkTsCheckerWebpackPlugin({
  706. async: isEnvDevelopment,
  707. typescript: {
  708. typescriptPath: resolve.sync('typescript', {
  709. basedir: paths.appNodeModules,
  710. }),
  711. configOverwrite: {
  712. compilerOptions: {
  713. sourceMap: isEnvProduction
  714. ? shouldUseSourceMap
  715. : isEnvDevelopment,
  716. skipLibCheck: true,
  717. inlineSourceMap: false,
  718. declarationMap: false,
  719. noEmit: true,
  720. incremental: true,
  721. tsBuildInfoFile: paths.appTsBuildInfoFile,
  722. },
  723. },
  724. context: paths.appPath,
  725. diagnosticOptions: {
  726. syntactic: true,
  727. },
  728. mode: 'write-references',
  729. // profile: true,
  730. },
  731. issue: {
  732. // This one is specifically to match during CI tests,
  733. // as micromatch doesn't match
  734. // '../cra-template-typescript/template/src/App.tsx'
  735. // otherwise.
  736. include: [
  737. { file: '../**/src/**/*.{ts,tsx}' },
  738. { file: '**/src/**/*.{ts,tsx}' },
  739. ],
  740. exclude: [
  741. { file: '**/src/**/__tests__/**' },
  742. { file: '**/src/**/?(*.){spec|test}.*' },
  743. { file: '**/src/setupProxy.*' },
  744. { file: '**/src/setupTests.*' },
  745. ],
  746. },
  747. logger: {
  748. infrastructure: 'silent',
  749. },
  750. }),
  751. !disableESLintPlugin &&
  752. new ESLintPlugin({
  753. // Plugin options
  754. extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
  755. formatter: require.resolve('react-dev-utils/eslintFormatter'),
  756. eslintPath: require.resolve('eslint'),
  757. failOnError: !(isEnvDevelopment && emitErrorsAsWarnings),
  758. context: paths.appSrc,
  759. cache: true,
  760. cacheLocation: path.resolve(
  761. paths.appNodeModules,
  762. '.cache/.eslintcache'
  763. ),
  764. // ESLint class options
  765. cwd: paths.appPath,
  766. resolvePluginsRelativeTo: __dirname,
  767. baseConfig: {
  768. extends: [require.resolve('eslint-config-react-app/base')],
  769. rules: {
  770. ...(!hasJsxRuntime && {
  771. 'react/react-in-jsx-scope': 'error',
  772. }),
  773. },
  774. },
  775. }),
  776. ].filter(Boolean),
  777. // Turn off performance processing because we utilize
  778. // our own hints via the FileSizeReporter
  779. performance: false,
  780. };
  781. };