webpack.config.js 29 KB

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