You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

683 lines
29 KiB

  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 eslint = require('eslint');
  28. const postcssNormalize = require('postcss-normalize');
  29. const appPackageJson = require(paths.appPackageJson);
  30. // Source maps are resource heavy and can cause out of memory issue for large source files.
  31. const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
  32. // Some apps do not need the benefits of saving a web request, so not inlining the chunk
  33. // makes for a smoother build process.
  34. const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
  35. const imageInlineSizeLimit = parseInt(
  36. process.env.IMAGE_INLINE_SIZE_LIMIT || '10000'
  37. );
  38. // Check if TypeScript is setup
  39. const useTypeScript = fs.existsSync(paths.appTsConfig);
  40. // style files regexes
  41. const cssRegex = /\.css$/;
  42. const cssModuleRegex = /\.module\.css$/;
  43. const sassRegex = /\.(scss|sass)$/;
  44. const sassModuleRegex = /\.module\.(scss|sass)$/;
  45. // This is the production and development configuration.
  46. // It is focused on developer experience, fast rebuilds, and a minimal bundle.
  47. module.exports = function(webpackEnv) {
  48. const isEnvDevelopment = webpackEnv === 'development';
  49. const isEnvProduction = webpackEnv === 'production';
  50. // Variable used for enabling profiling in Production
  51. // passed into alias object. Uses a flag if passed into the build command
  52. const isEnvProductionProfile =
  53. isEnvProduction && process.argv.includes('--profile');
  54. // Webpack uses `publicPath` to determine where the app is being served from.
  55. // It requires a trailing slash, or the file assets will get an incorrect path.
  56. // In development, we always serve from the root. This makes config easier.
  57. const publicPath = isEnvProduction
  58. ? paths.servedPath
  59. : isEnvDevelopment && '/';
  60. // Some apps do not use client-side routing with pushState.
  61. // For these, "homepage" can be set to "." to enable relative asset paths.
  62. const shouldUseRelativeAssetPaths = publicPath === './';
  63. // `publicUrl` is just like `publicPath`, but we will provide it to our app
  64. // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
  65. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
  66. const publicUrl = isEnvProduction
  67. ? publicPath.slice(0, -1)
  68. : isEnvDevelopment && '';
  69. // Get environment variables to inject into our app.
  70. const env = getClientEnvironment(publicUrl);
  71. // common function to get style loaders
  72. const getStyleLoaders = (cssOptions, preProcessor) => {
  73. const loaders = [
  74. isEnvDevelopment && require.resolve('style-loader'),
  75. isEnvProduction && {
  76. loader: MiniCssExtractPlugin.loader,
  77. options: shouldUseRelativeAssetPaths ? { publicPath: '../../' } : {},
  78. },
  79. {
  80. loader: require.resolve('css-loader'),
  81. options: cssOptions,
  82. },
  83. {
  84. // Options for PostCSS as we reference these options twice
  85. // Adds vendor prefixing based on your specified browser support in
  86. // package.json
  87. loader: require.resolve('postcss-loader'),
  88. options: {
  89. // Necessary for external CSS imports to work
  90. // https://github.com/facebook/create-react-app/issues/2677
  91. ident: 'postcss',
  92. plugins: () => [
  93. require('postcss-flexbugs-fixes'),
  94. require('postcss-preset-env')({
  95. autoprefixer: {
  96. flexbox: 'no-2009',
  97. },
  98. stage: 3,
  99. }),
  100. // Adds PostCSS Normalize as the reset css with default options,
  101. // so that it honors browserslist config in package.json
  102. // which in turn let's users customize the target behavior as per their needs.
  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. // Use multi-process parallel running to improve the build speed
  234. // Default number of concurrent runs: os.cpus().length - 1
  235. // Disabled on WSL (Windows Subsystem for Linux) due to an issue with Terser
  236. // https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
  237. parallel: !isWsl,
  238. // Enable file caching
  239. cache: true,
  240. sourceMap: shouldUseSourceMap,
  241. }),
  242. // This is only used in production mode
  243. new OptimizeCSSAssetsPlugin({
  244. cssProcessorOptions: {
  245. parser: safePostCssParser,
  246. map: shouldUseSourceMap
  247. ? {
  248. // `inline: false` forces the sourcemap to be output into a
  249. // separate file
  250. inline: false,
  251. // `annotation: true` appends the sourceMappingURL to the end of
  252. // the css file, helping the browser find the sourcemap
  253. annotation: true,
  254. }
  255. : false,
  256. },
  257. }),
  258. ],
  259. // Automatically split vendor and commons
  260. // https://twitter.com/wSokra/status/969633336732905474
  261. // https://medium.com/webpack/webpack-4-code-splitting-chunk-graph-and-the-splitchunks-optimization-be739a861366
  262. splitChunks: {
  263. // chunks: 'all',
  264. // name: false,
  265. cacheGroups: {
  266. default: false
  267. }
  268. },
  269. // Keep the runtime chunk separated to enable long term caching
  270. // https://twitter.com/wSokra/status/969679223278505985
  271. // https://github.com/facebook/create-react-app/issues/5358
  272. runtimeChunk: {
  273. name: entrypoint => `runtime-${entrypoint.name}`,
  274. },
  275. },
  276. resolve: {
  277. // This allows you to set a fallback for where Webpack should look for modules.
  278. // We placed these paths second because we want `node_modules` to "win"
  279. // if there are any conflicts. This matches Node resolution mechanism.
  280. // https://github.com/facebook/create-react-app/issues/253
  281. modules: ['node_modules', paths.appNodeModules].concat(
  282. modules.additionalModulePaths || []
  283. ),
  284. // These are the reasonable defaults supported by the Node ecosystem.
  285. // We also include JSX as a common component filename extension to support
  286. // some tools, although we do not recommend using it, see:
  287. // https://github.com/facebook/create-react-app/issues/290
  288. // `web` extension prefixes have been added for better support
  289. // for React Native Web.
  290. extensions: paths.moduleFileExtensions
  291. .map(ext => `.${ext}`)
  292. .filter(ext => useTypeScript || !ext.includes('ts')),
  293. alias: {
  294. // Support React Native Web
  295. // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
  296. 'react-native': 'react-native-web',
  297. // Allows for better profiling with ReactDevTools
  298. ...(isEnvProductionProfile && {
  299. 'react-dom$': 'react-dom/profiling',
  300. 'scheduler/tracing': 'scheduler/tracing-profiling',
  301. }),
  302. ...(modules.webpackAliases || {}),
  303. },
  304. plugins: [
  305. // Adds support for installing with Plug'n'Play, leading to faster installs and adding
  306. // guards against forgotten dependencies and such.
  307. PnpWebpackPlugin,
  308. // Prevents users from importing files from outside of src/ (or node_modules/).
  309. // This often causes confusion because we only process files within src/ with babel.
  310. // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
  311. // please link the files into your node_modules/ and let module-resolution kick in.
  312. // Make sure your source files are compiled, as they will not be processed in any way.
  313. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
  314. ],
  315. },
  316. resolveLoader: {
  317. plugins: [
  318. // Also related to Plug'n'Play, but this time it tells Webpack to load its loaders
  319. // from the current package.
  320. PnpWebpackPlugin.moduleLoader(module),
  321. ],
  322. },
  323. module: {
  324. strictExportPresence: true,
  325. rules: [
  326. // Disable require.ensure as it's not a standard language feature.
  327. { parser: { requireEnsure: false } },
  328. // First, run the linter.
  329. // It's important to do this before Babel processes the JS.
  330. {
  331. test: /\.(js|mjs|jsx|ts|tsx)$/,
  332. enforce: 'pre',
  333. use: [
  334. {
  335. options: {
  336. cache: true,
  337. formatter: require.resolve('react-dev-utils/eslintFormatter'),
  338. eslintPath: require.resolve('eslint'),
  339. resolvePluginsRelativeTo: __dirname,
  340. },
  341. loader: require.resolve('eslint-loader'),
  342. },
  343. ],
  344. include: paths.appSrc,
  345. },
  346. {
  347. // "oneOf" will traverse all following loaders until one will
  348. // match the requirements. When no loader matches it will fall
  349. // back to the "file" loader at the end of the loader list.
  350. oneOf: [
  351. // "url" loader works like "file" loader except that it embeds assets
  352. // smaller than specified limit in bytes as data URLs to avoid requests.
  353. // A missing `test` is equivalent to a match.
  354. {
  355. test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
  356. loader: require.resolve('url-loader'),
  357. options: {
  358. limit: imageInlineSizeLimit,
  359. name: 'static/media/[name].[hash:8].[ext]',
  360. },
  361. },
  362. // Process application JS with Babel.
  363. // The preset includes JSX, Flow, TypeScript, and some ESnext features.
  364. {
  365. test: /\.(js|mjs|jsx|ts|tsx)$/,
  366. include: paths.appSrc,
  367. loader: require.resolve('babel-loader'),
  368. options: {
  369. customize: require.resolve(
  370. 'babel-preset-react-app/webpack-overrides'
  371. ),
  372. plugins: [
  373. [
  374. require.resolve('babel-plugin-named-asset-import'),
  375. {
  376. loaderMap: {
  377. svg: {
  378. ReactComponent:
  379. '@svgr/webpack?-svgo,+titleProp,+ref![path]',
  380. },
  381. },
  382. },
  383. ],
  384. ],
  385. // This is a feature of `babel-loader` for webpack (not Babel itself).
  386. // It enables caching results in ./node_modules/.cache/babel-loader/
  387. // directory for faster rebuilds.
  388. cacheDirectory: true,
  389. // See #6846 for context on why cacheCompression is disabled
  390. cacheCompression: false,
  391. compact: isEnvProduction,
  392. },
  393. },
  394. // Process any JS outside of the app with Babel.
  395. // Unlike the application JS, we only compile the standard ES features.
  396. {
  397. test: /\.(js|mjs)$/,
  398. exclude: /@babel(?:\/|\\{1,2})runtime/,
  399. loader: require.resolve('babel-loader'),
  400. options: {
  401. babelrc: false,
  402. configFile: false,
  403. compact: false,
  404. presets: [
  405. [
  406. require.resolve('babel-preset-react-app/dependencies'),
  407. { helpers: true },
  408. ],
  409. ],
  410. cacheDirectory: true,
  411. // See #6846 for context on why cacheCompression is disabled
  412. cacheCompression: false,
  413. // If an error happens in a package, it's possible to be
  414. // because it was compiled. Thus, we don't want the browser
  415. // debugger to show the original code. Instead, the code
  416. // being evaluated would be much more helpful.
  417. sourceMaps: false,
  418. },
  419. },
  420. // "postcss" loader applies autoprefixer to our CSS.
  421. // "css" loader resolves paths in CSS and adds assets as dependencies.
  422. // "style" loader turns CSS into JS modules that inject <style> tags.
  423. // In production, we use MiniCSSExtractPlugin to extract that CSS
  424. // to a file, but in development "style" loader enables hot editing
  425. // of CSS.
  426. // By default we support CSS Modules with the extension .module.css
  427. {
  428. test: cssRegex,
  429. exclude: cssModuleRegex,
  430. use: getStyleLoaders({
  431. importLoaders: 1,
  432. sourceMap: isEnvProduction && shouldUseSourceMap,
  433. }),
  434. // Don't consider CSS imports dead code even if the
  435. // containing package claims to have no side effects.
  436. // Remove this when webpack adds a warning or an error for this.
  437. // See https://github.com/webpack/webpack/issues/6571
  438. sideEffects: true,
  439. },
  440. // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
  441. // using the extension .module.css
  442. {
  443. test: cssModuleRegex,
  444. use: getStyleLoaders({
  445. importLoaders: 1,
  446. sourceMap: isEnvProduction && shouldUseSourceMap,
  447. modules: true,
  448. getLocalIdent: getCSSModuleLocalIdent,
  449. }),
  450. },
  451. // Opt-in support for SASS (using .scss or .sass extensions).
  452. // By default we support SASS Modules with the
  453. // extensions .module.scss or .module.sass
  454. {
  455. test: sassRegex,
  456. exclude: sassModuleRegex,
  457. use: getStyleLoaders(
  458. {
  459. importLoaders: 2,
  460. sourceMap: isEnvProduction && shouldUseSourceMap,
  461. },
  462. 'sass-loader'
  463. ),
  464. // Don't consider CSS imports dead code even if the
  465. // containing package claims to have no side effects.
  466. // Remove this when webpack adds a warning or an error for this.
  467. // See https://github.com/webpack/webpack/issues/6571
  468. sideEffects: true,
  469. },
  470. // Adds support for CSS Modules, but using SASS
  471. // using the extension .module.scss or .module.sass
  472. {
  473. test: sassModuleRegex,
  474. use: getStyleLoaders(
  475. {
  476. importLoaders: 2,
  477. sourceMap: isEnvProduction && shouldUseSourceMap,
  478. modules: true,
  479. getLocalIdent: getCSSModuleLocalIdent,
  480. },
  481. 'sass-loader'
  482. ),
  483. },
  484. // "file" loader makes sure those assets get served by WebpackDevServer.
  485. // When you `import` an asset, you get its (virtual) filename.
  486. // In production, they would get copied to the `build` folder.
  487. // This loader doesn't use a "test" so it will catch all modules
  488. // that fall through the other loaders.
  489. {
  490. loader: require.resolve('file-loader'),
  491. // Exclude `js` files to keep "css" loader working as it injects
  492. // its runtime that would otherwise be processed through "file" loader.
  493. // Also exclude `html` and `json` extensions so they get processed
  494. // by webpacks internal loaders.
  495. exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/],
  496. options: {
  497. name: 'static/media/[name].[hash:8].[ext]',
  498. },
  499. },
  500. // ** STOP ** Are you adding a new loader?
  501. // Make sure to add the new loader(s) before the "file" loader.
  502. ],
  503. },
  504. ],
  505. },
  506. plugins: [
  507. // Generates an `index.html` file with the <script> injected.
  508. new HtmlWebpackPlugin(
  509. Object.assign(
  510. {},
  511. {
  512. inject: true,
  513. template: paths.appHtml,
  514. },
  515. isEnvProduction
  516. ? {
  517. minify: {
  518. removeComments: true,
  519. collapseWhitespace: true,
  520. removeRedundantAttributes: true,
  521. useShortDoctype: true,
  522. removeEmptyAttributes: true,
  523. removeStyleLinkTypeAttributes: true,
  524. keepClosingSlash: true,
  525. minifyJS: true,
  526. minifyCSS: true,
  527. minifyURLs: true,
  528. },
  529. }
  530. : undefined
  531. )
  532. ),
  533. // Inlines the webpack runtime script. This script is too small to warrant
  534. // a network request.
  535. // https://github.com/facebook/create-react-app/issues/5358
  536. isEnvProduction &&
  537. shouldInlineRuntimeChunk &&
  538. new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]),
  539. // Makes some environment variables available in index.html.
  540. // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
  541. // <link rel="icon" href="%PUBLIC_URL%/favicon.ico">
  542. // In production, it will be an empty string unless you specify "homepage"
  543. // in `package.json`, in which case it will be the pathname of that URL.
  544. // In development, this will be an empty string.
  545. new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
  546. // This gives some necessary context to module not found errors, such as
  547. // the requesting resource.
  548. new ModuleNotFoundPlugin(paths.appPath),
  549. // Makes some environment variables available to the JS code, for example:
  550. // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  551. // It is absolutely essential that NODE_ENV is set to production
  552. // during a production build.
  553. // Otherwise React will be compiled in the very slow development mode.
  554. new webpack.DefinePlugin(env.stringified),
  555. // This is necessary to emit hot updates (currently CSS only):
  556. isEnvDevelopment && new webpack.HotModuleReplacementPlugin(),
  557. // Watcher doesn't work well if you mistype casing in a path so we use
  558. // a plugin that prints an error when you attempt to do this.
  559. // See https://github.com/facebook/create-react-app/issues/240
  560. isEnvDevelopment && new CaseSensitivePathsPlugin(),
  561. // If you require a missing module and then `npm install` it, you still have
  562. // to restart the development server for Webpack to discover it. This plugin
  563. // makes the discovery automatic so you don't have to restart.
  564. // See https://github.com/facebook/create-react-app/issues/186
  565. isEnvDevelopment &&
  566. new WatchMissingNodeModulesPlugin(paths.appNodeModules),
  567. isEnvProduction &&
  568. new MiniCssExtractPlugin({
  569. // Options similar to the same options in webpackOptions.output
  570. // both options are optional
  571. filename: 'static/css/[name].[contenthash:8].css',
  572. chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
  573. }),
  574. // Generate an asset manifest file with the following content:
  575. // - "files" key: Mapping of all asset filenames to their corresponding
  576. // output file so that tools can pick it up without having to parse
  577. // `index.html`
  578. // - "entrypoints" key: Array of files which are included in `index.html`,
  579. // can be used to reconstruct the HTML if necessary
  580. new ManifestPlugin({
  581. fileName: 'asset-manifest.json',
  582. publicPath: publicPath,
  583. generate: (seed, files, entrypoints) => {
  584. const manifestFiles = files.reduce((manifest, file) => {
  585. manifest[file.name] = file.path;
  586. return manifest;
  587. }, seed);
  588. const entrypointFiles = entrypoints.main.filter(
  589. fileName => !fileName.endsWith('.map')
  590. );
  591. return {
  592. files: manifestFiles,
  593. entrypoints: entrypointFiles,
  594. };
  595. },
  596. }),
  597. // Moment.js is an extremely popular library that bundles large locale files
  598. // by default due to how Webpack interprets its code. This is a practical
  599. // solution that requires the user to opt into importing specific locales.
  600. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  601. // You can remove this if you don't use Moment.js:
  602. new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  603. // Generate a service worker script that will precache, and keep up to date,
  604. // the HTML & assets that are part of the Webpack build.
  605. isEnvProduction &&
  606. new WorkboxWebpackPlugin.GenerateSW({
  607. clientsClaim: true,
  608. exclude: [/\.map$/, /asset-manifest\.json$/],
  609. importWorkboxFrom: 'cdn',
  610. navigateFallback: publicUrl + '/index.html',
  611. navigateFallbackBlacklist: [
  612. // Exclude URLs starting with /_, as they're likely an API call
  613. new RegExp('^/_'),
  614. // Exclude any URLs whose last part seems to be a file extension
  615. // as they're likely a resource and not a SPA route.
  616. // URLs containing a "?" character won't be blacklisted as they're likely
  617. // a route with query params (e.g. auth callbacks).
  618. new RegExp('/[^/?]+\\.[^/]+$'),
  619. ],
  620. }),
  621. // TypeScript type checking
  622. useTypeScript &&
  623. new ForkTsCheckerWebpackPlugin({
  624. typescript: resolve.sync('typescript', {
  625. basedir: paths.appNodeModules,
  626. }),
  627. async: isEnvDevelopment,
  628. useTypescriptIncrementalApi: true,
  629. checkSyntacticErrors: true,
  630. resolveModuleNameModule: process.versions.pnp
  631. ? `${__dirname}/pnpTs.js`
  632. : undefined,
  633. resolveTypeReferenceDirectiveModule: process.versions.pnp
  634. ? `${__dirname}/pnpTs.js`
  635. : undefined,
  636. tsconfig: paths.appTsConfig,
  637. reportFiles: [
  638. '**',
  639. '!**/__tests__/**',
  640. '!**/?(*.)(spec|test).*',
  641. '!**/src/setupProxy.*',
  642. '!**/src/setupTests.*',
  643. ],
  644. silent: true,
  645. // The formatter is invoked directly in WebpackDevServerUtils during development
  646. formatter: isEnvProduction ? typescriptFormatter : undefined,
  647. }),
  648. ].filter(Boolean),
  649. // Some libraries import Node modules but don't use them in the browser.
  650. // Tell Webpack to provide empty mocks for them so importing them works.
  651. node: {
  652. module: 'empty',
  653. dgram: 'empty',
  654. dns: 'mock',
  655. fs: 'empty',
  656. http2: 'empty',
  657. net: 'empty',
  658. tls: 'empty',
  659. child_process: 'empty',
  660. },
  661. // Turn off performance processing because we utilize
  662. // our own hints via the FileSizeReporter
  663. performance: false,
  664. };
  665. };