视频播放器仓库

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