webpack.config.js 26 KB

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