webpack.config.js 29 KB

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