webpack.config.js 32 KB

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