Aucune description

webpack.config.js 27KB

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