webpack.config.js 29 KB

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