webpack.config.js 28 KB

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