webpack.config.js 30 KB

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