webpack.config.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. const fs = require('fs');
  2. const path = require('path');
  3. const webpack = require('webpack');
  4. const resolve = require('resolve');
  5. const PnpWebpackPlugin = require('pnp-webpack-plugin');
  6. const HtmlWebpackPlugin = require('html-webpack-plugin');
  7. const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin');
  8. const InlineChunkHtmlPlugin = require('react-dev-utils/InlineChunkHtmlPlugin');
  9. const TerserPlugin = require('terser-webpack-plugin');
  10. const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  11. const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
  12. const safePostCssParser = require('postcss-safe-parser');
  13. const ManifestPlugin = require('webpack-manifest-plugin');
  14. const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
  15. const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
  16. const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
  17. const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
  18. const getCSSModuleLocalIdent = require('react-dev-utils/getCSSModuleLocalIdent');
  19. const paths = require('./paths');
  20. const modules = require('./modules');
  21. const getClientEnvironment = require('./env');
  22. const ModuleNotFoundPlugin = require('react-dev-utils/ModuleNotFoundPlugin');
  23. const ForkTsCheckerWebpackPlugin = require('react-dev-utils/ForkTsCheckerWebpackPlugin');
  24. const typescriptFormatter = require('react-dev-utils/typescriptFormatter');
  25. const CompressionPlugin = require('compression-webpack-plugin');
  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. const shouldUseSourceMap = false;
  31. // Some apps do not need the benefits of saving a web request, so not inlining the chunk
  32. // makes for a smoother build process.
  33. const shouldInlineRuntimeChunk = process.env.INLINE_RUNTIME_CHUNK !== 'false';
  34. const isExtendingEslintConfig = process.env.EXTEND_ESLINT === 'true';
  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. // We will provide `paths.publicUrlOrPath` to our app
  55. // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
  56. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
  57. // Get environment variables to inject into our app.
  58. const env = getClientEnvironment(paths.publicUrlOrPath.slice(0, -1));
  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. // css is located in `static/css`, use '../../' to locate index.html folder
  66. // in production `paths.publicUrlOrPath` can be a relative path
  67. options: paths.publicUrlOrPath.startsWith('.')
  68. ? { publicPath: '../../' }
  69. : {},
  70. },
  71. {
  72. loader: require.resolve('css-loader'),
  73. options: cssOptions,
  74. },
  75. {
  76. // Options for PostCSS as we reference these options twice
  77. // Adds vendor prefixing based on your specified browser support in
  78. // package.json
  79. loader: require.resolve('postcss-loader'),
  80. options: {
  81. // Necessary for external CSS imports to work
  82. // https://github.com/facebook/create-react-app/issues/2677
  83. ident: 'postcss',
  84. plugins: () => [
  85. require('postcss-flexbugs-fixes'),
  86. require('postcss-preset-env')({
  87. autoprefixer: {
  88. flexbox: 'no-2009',
  89. },
  90. stage: 3,
  91. }),
  92. // Adds PostCSS Normalize as the reset css with default options,
  93. // so that it honors browserslist config in package.json
  94. // which in turn let's users customize the target behavior as per their needs.
  95. postcssNormalize(),
  96. ],
  97. sourceMap: isEnvProduction && shouldUseSourceMap,
  98. },
  99. },
  100. ].filter(Boolean);
  101. if (preProcessor) {
  102. loaders.push(
  103. {
  104. loader: require.resolve('resolve-url-loader'),
  105. options: {
  106. sourceMap: isEnvProduction && shouldUseSourceMap,
  107. },
  108. },
  109. {
  110. loader: require.resolve(preProcessor),
  111. options: {
  112. sourceMap: true,
  113. },
  114. }
  115. );
  116. }
  117. return loaders;
  118. };
  119. return {
  120. mode: isEnvProduction ? 'production' : isEnvDevelopment && 'development',
  121. // Stop compilation early in production
  122. bail: isEnvProduction,
  123. devtool: isEnvProduction
  124. ? shouldUseSourceMap
  125. ? 'source-map'
  126. : false
  127. : isEnvDevelopment && 'cheap-module-source-map',
  128. // These are the "entry points" to our application.
  129. // This means they will be the "root" imports that are included in JS bundle.
  130. entry: [
  131. // Include an alternative client for WebpackDevServer. A client's job is to
  132. // connect to WebpackDevServer by a socket and get notified about changes.
  133. // When you save a file, the client will either apply hot updates (in case
  134. // of CSS changes), or refresh the page (in case of JS changes). When you
  135. // make a syntax error, this client will display a syntax error overlay.
  136. // Note: instead of the default WebpackDevServer client, we use a custom one
  137. // to bring better experience for Create React App users. You can replace
  138. // the line below with these two lines if you prefer the stock client:
  139. // require.resolve('webpack-dev-server/client') + '?/',
  140. // require.resolve('webpack/hot/dev-server'),
  141. isEnvDevelopment &&
  142. require.resolve('react-dev-utils/webpackHotDevClient'),
  143. // Finally, this is your app's code:
  144. paths.appIndexJs,
  145. // We include the app code last so that if there is a runtime error during
  146. // initialization, it doesn't blow up the WebpackDevServer client, and
  147. // changing JS code would still trigger a refresh.
  148. ].filter(Boolean),
  149. output: {
  150. // The build folder.
  151. path: isEnvProduction ? paths.appBuild : undefined,
  152. // Add /* filename */ comments to generated require()s in the output.
  153. pathinfo: isEnvDevelopment,
  154. // There will be one main bundle, and one file per asynchronous chunk.
  155. // In development, it does not produce real files.
  156. filename: isEnvProduction
  157. ? 'static/js/[name].[contenthash:8].js'
  158. : isEnvDevelopment && 'static/js/bundle.js',
  159. // TODO: remove this when upgrading to webpack 5
  160. futureEmitAssets: true,
  161. // There are also additional JS chunk files if you use code splitting.
  162. chunkFilename: isEnvProduction
  163. ? 'static/js/[name].[contenthash:8].chunk.js'
  164. : isEnvDevelopment && 'static/js/[name].chunk.js',
  165. // webpack uses `publicPath` to determine where the app is being served from.
  166. // It requires a trailing slash, or the file assets will get an incorrect path.
  167. // We inferred the "public path" (such as / or /my-project) from homepage.
  168. publicPath: paths.publicUrlOrPath,
  169. // Point sourcemap entries to original disk location (format as URL on Windows)
  170. devtoolModuleFilenameTemplate: isEnvProduction
  171. ? info =>
  172. path
  173. .relative(paths.appSrc, info.absoluteResourcePath)
  174. .replace(/\\/g, '/')
  175. : isEnvDevelopment &&
  176. (info => path.resolve(info.absoluteResourcePath).replace(/\\/g, '/')),
  177. // Prevents conflicts when multiple webpack runtimes (from different apps)
  178. // are used on the same page.
  179. jsonpFunction: `webpackJsonp${appPackageJson.name}`,
  180. // this defaults to 'window', but by setting it to 'this' then
  181. // module chunks which are built will work in web workers as well.
  182. globalObject: 'this',
  183. },
  184. optimization: {
  185. minimize: isEnvProduction,
  186. minimizer: [
  187. // This is only used in production mode
  188. new TerserPlugin({
  189. terserOptions: {
  190. parse: {
  191. // We want terser to parse ecma 8 code. However, we don't want it
  192. // to apply any minification steps that turns valid ecma 5 code
  193. // into invalid ecma 5 code. This is why the 'compress' and 'output'
  194. // sections only apply transformations that are ecma 5 safe
  195. // https://github.com/facebook/create-react-app/pull/4234
  196. ecma: 8,
  197. },
  198. compress: {
  199. ecma: 5,
  200. warnings: false,
  201. // Disabled because of an issue with Uglify breaking seemingly valid code:
  202. // https://github.com/facebook/create-react-app/issues/2376
  203. // Pending further investigation:
  204. // https://github.com/mishoo/UglifyJS2/issues/2011
  205. comparisons: false,
  206. // Disabled because of an issue with Terser breaking valid code:
  207. // https://github.com/facebook/create-react-app/issues/5250
  208. // Pending further investigation:
  209. // https://github.com/terser-js/terser/issues/120
  210. inline: 2,
  211. },
  212. mangle: {
  213. safari10: true,
  214. },
  215. // Added for profiling in devtools
  216. keep_classnames: isEnvProductionProfile,
  217. keep_fnames: isEnvProductionProfile,
  218. output: {
  219. ecma: 5,
  220. comments: false,
  221. // Turned on because emoji and regex is not minified properly using default
  222. // https://github.com/facebook/create-react-app/issues/2488
  223. ascii_only: true,
  224. },
  225. },
  226. sourceMap: shouldUseSourceMap,
  227. parallel: true, //此处为新增配置
  228. extractComments: false,
  229. }),
  230. // This is only used in production mode
  231. new OptimizeCSSAssetsPlugin({
  232. cssProcessorOptions: {
  233. parser: safePostCssParser,
  234. map: shouldUseSourceMap
  235. ? {
  236. // `inline: false` forces the sourcemap to be output into a
  237. // separate file
  238. inline: false,
  239. // `annotation: true` appends the sourceMappingURL to the end of
  240. // the css file, helping the browser find the sourcemap
  241. annotation: true,
  242. }
  243. : false,
  244. },
  245. cssProcessorPluginOptions: {
  246. preset: ['default', { minifyFontValues: { removeQuotes: 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. '@': paths.appSrc
  292. // 'store': path.appStore
  293. },
  294. plugins: [
  295. // Adds support for installing with Plug'n'Play, leading to faster installs and adding
  296. // guards against forgotten dependencies and such.
  297. PnpWebpackPlugin,
  298. // Prevents users from importing files from outside of src/ (or node_modules/).
  299. // This often causes confusion because we only process files within src/ with babel.
  300. // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
  301. // please link the files into your node_modules/ and let module-resolution kick in.
  302. // Make sure your source files are compiled, as they will not be processed in any way.
  303. new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
  304. ],
  305. },
  306. resolveLoader: {
  307. plugins: [
  308. // Also related to Plug'n'Play, but this time it tells webpack to load its loaders
  309. // from the current package.
  310. PnpWebpackPlugin.moduleLoader(module),
  311. ],
  312. },
  313. module: {
  314. strictExportPresence: true,
  315. rules: [
  316. // Disable require.ensure as it's not a standard language feature.
  317. { parser: { requireEnsure: false } },
  318. // First, run the linter.
  319. // It's important to do this before Babel processes the JS.
  320. // {
  321. // test: /\.(js|mjs|jsx|ts|tsx)$/,
  322. // enforce: 'pre',
  323. // use: [
  324. // {
  325. // options: {
  326. // cache: false,
  327. // formatter: require.resolve('react-dev-utils/eslintFormatter'),
  328. // eslintPath: require.resolve('eslint'),
  329. // resolvePluginsRelativeTo: __dirname,
  330. // },
  331. // loader: require.resolve('eslint-loader'),
  332. // },
  333. // ],
  334. // include: paths.appSrc,
  335. // },
  336. {
  337. // "oneOf" will traverse all following loaders until one will
  338. // match the requirements. When no loader matches it will fall
  339. // back to the "file" loader at the end of the loader list.
  340. oneOf: [
  341. {
  342. test: /\.svg$/,
  343. loader: "svg-sprite-loader",
  344. include: path.resolve(__dirname, "../src/assets/icons"), //只处理指定svg的文件(所有使用的svg文件放到该文件夹下)
  345. options: {
  346. symbolId: "icon-[name]" //symbolId和use使用的名称对应 <use xlinkHref={"#icon-" + iconClass} />
  347. }
  348. },
  349. // "url" loader works like "file" loader except that it embeds assets
  350. // smaller than specified limit in bytes as data URLs to avoid requests.
  351. // A missing `test` is equivalent to a match.
  352. {
  353. test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
  354. loader: require.resolve('url-loader'),
  355. options: {
  356. limit: imageInlineSizeLimit,
  357. name: 'static/media/[name].[hash:8].[ext]',
  358. },
  359. },
  360. // Process application JS with Babel.
  361. // The preset includes JSX, Flow, TypeScript, and some ESnext features.
  362. {
  363. test: /\.(js|mjs|jsx|ts|tsx)$/,
  364. include: paths.appSrc,
  365. loader: require.resolve('babel-loader'),
  366. options: {
  367. customize: require.resolve(
  368. 'babel-preset-react-app/webpack-overrides'
  369. ),
  370. plugins: [
  371. [
  372. require.resolve('babel-plugin-named-asset-import'),
  373. {
  374. loaderMap: {
  375. svg: {
  376. ReactComponent:
  377. '@svgr/webpack?-svgo,+titleProp,+ref![path]',
  378. },
  379. },
  380. },
  381. ]
  382. ],
  383. // This is a feature of `babel-loader` for webpack (not Babel itself).
  384. // It enables caching results in ./node_modules/.cache/babel-loader/
  385. // directory for faster rebuilds.
  386. cacheDirectory: true,
  387. // See #6846 for context on why cacheCompression is disabled
  388. cacheCompression: false,
  389. compact: isEnvProduction,
  390. },
  391. },
  392. // Process any JS outside of the app with Babel.
  393. // Unlike the application JS, we only compile the standard ES features.
  394. {
  395. test: /\.(js|mjs)$/,
  396. exclude: /@babel(?:\/|\\{1,2})runtime/,
  397. loader: require.resolve('babel-loader'),
  398. options: {
  399. babelrc: false,
  400. configFile: false,
  401. compact: false,
  402. presets: [
  403. [
  404. require.resolve('babel-preset-react-app/dependencies'),
  405. { helpers: true },
  406. ],
  407. ],
  408. cacheDirectory: true,
  409. // See #6846 for context on why cacheCompression is disabled
  410. cacheCompression: false,
  411. // Babel sourcemaps are needed for debugging into node_modules
  412. // code. Without the options below, debuggers like VSCode
  413. // show incorrect code and set breakpoints on the wrong lines.
  414. sourceMaps: shouldUseSourceMap,
  415. inputSourceMap: shouldUseSourceMap,
  416. },
  417. },
  418. // "postcss" loader applies autoprefixer to our CSS.
  419. // "css" loader resolves paths in CSS and adds assets as dependencies.
  420. // "style" loader turns CSS into JS modules that inject <style> tags.
  421. // In production, we use MiniCSSExtractPlugin to extract that CSS
  422. // to a file, but in development "style" loader enables hot editing
  423. // of CSS.
  424. // By default we support CSS Modules with the extension .module.css
  425. {
  426. test: cssRegex,
  427. exclude: cssModuleRegex,
  428. use: getStyleLoaders({
  429. importLoaders: 1,
  430. sourceMap: isEnvProduction && shouldUseSourceMap,
  431. }),
  432. // Don't consider CSS imports dead code even if the
  433. // containing package claims to have no side effects.
  434. // Remove this when webpack adds a warning or an error for this.
  435. // See https://github.com/webpack/webpack/issues/6571
  436. sideEffects: true,
  437. },
  438. // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
  439. // using the extension .module.css
  440. {
  441. test: cssModuleRegex,
  442. use: getStyleLoaders({
  443. importLoaders: 1,
  444. sourceMap: isEnvProduction && shouldUseSourceMap,
  445. modules: {
  446. getLocalIdent: getCSSModuleLocalIdent,
  447. },
  448. }),
  449. },
  450. // Opt-in support for SASS (using .scss or .sass extensions).
  451. // By default we support SASS Modules with the
  452. // extensions .module.scss or .module.sass
  453. {
  454. test: sassRegex,
  455. exclude: sassModuleRegex,
  456. use: getStyleLoaders(
  457. {
  458. importLoaders: 3,
  459. sourceMap: isEnvProduction && shouldUseSourceMap,
  460. },
  461. 'sass-loader'
  462. ),
  463. // Don't consider CSS imports dead code even if the
  464. // containing package claims to have no side effects.
  465. // Remove this when webpack adds a warning or an error for this.
  466. // See https://github.com/webpack/webpack/issues/6571
  467. sideEffects: true,
  468. },
  469. // Adds support for CSS Modules, but using SASS
  470. // using the extension .module.scss or .module.sass
  471. {
  472. test: sassModuleRegex,
  473. use: getStyleLoaders(
  474. {
  475. importLoaders: 3,
  476. sourceMap: isEnvProduction && shouldUseSourceMap,
  477. modules: {
  478. getLocalIdent: getCSSModuleLocalIdent,
  479. },
  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. // 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. new InterpolateHtmlPlugin(HtmlWebpackPlugin, env.raw),
  545. // This gives some necessary context to module not found errors, such as
  546. // the requesting resource.
  547. new ModuleNotFoundPlugin(paths.appPath),
  548. // Makes some environment variables available to the JS code, for example:
  549. // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
  550. // It is absolutely essential that NODE_ENV is set to production
  551. // during a production build.
  552. // Otherwise React will be compiled in the very slow development mode.
  553. new webpack.DefinePlugin(env.stringified),
  554. // This is necessary to emit hot updates (currently CSS only):
  555. isEnvDevelopment && new webpack.HotModuleReplacementPlugin(),
  556. // Watcher doesn't work well if you mistype casing in a path so we use
  557. // a plugin that prints an error when you attempt to do this.
  558. // See https://github.com/facebook/create-react-app/issues/240
  559. isEnvDevelopment && new CaseSensitivePathsPlugin(),
  560. // If you require a missing module and then `npm install` it, you still have
  561. // to restart the development server for webpack to discover it. This plugin
  562. // makes the discovery automatic so you don't have to restart.
  563. // See https://github.com/facebook/create-react-app/issues/186
  564. isEnvDevelopment &&
  565. new WatchMissingNodeModulesPlugin(paths.appNodeModules),
  566. isEnvProduction &&
  567. new MiniCssExtractPlugin({
  568. // Options similar to the same options in webpackOptions.output
  569. // both options are optional
  570. filename: 'static/css/[name].[contenthash:8].css',
  571. chunkFilename: 'static/css/[name].[contenthash:8].chunk.css',
  572. }),
  573. // Generate an asset manifest file with the following content:
  574. // - "files" key: Mapping of all asset filenames to their corresponding
  575. // output file so that tools can pick it up without having to parse
  576. // `index.html`
  577. // - "entrypoints" key: Array of files which are included in `index.html`,
  578. // can be used to reconstruct the HTML if necessary
  579. new ManifestPlugin({
  580. fileName: 'asset-manifest.json',
  581. publicPath: paths.publicUrlOrPath,
  582. generate: (seed, files, entrypoints) => {
  583. const manifestFiles = files.reduce((manifest, file) => {
  584. manifest[file.name] = file.path;
  585. return manifest;
  586. }, seed);
  587. const entrypointFiles = entrypoints.main.filter(
  588. fileName => !fileName.endsWith('.map')
  589. );
  590. return {
  591. files: manifestFiles,
  592. entrypoints: entrypointFiles,
  593. };
  594. },
  595. }),
  596. // Moment.js is an extremely popular library that bundles large locale files
  597. // by default due to how webpack interprets its code. This is a practical
  598. // solution that requires the user to opt into importing specific locales.
  599. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
  600. // You can remove this if you don't use Moment.js:
  601. new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  602. // Generate a service worker script that will precache, and keep up to date,
  603. // the HTML & assets that are part of the webpack build.
  604. isEnvProduction &&
  605. new WorkboxWebpackPlugin.GenerateSW({
  606. clientsClaim: true,
  607. exclude: [/\.map$/, /asset-manifest\.json$/],
  608. importWorkboxFrom: 'cdn',
  609. navigateFallback: paths.publicUrlOrPath + 'index.html',
  610. navigateFallbackBlacklist: [
  611. // Exclude URLs starting with /_, as they're likely an API call
  612. new RegExp('^/_'),
  613. // Exclude any URLs whose last part seems to be a file extension
  614. // as they're likely a resource and not a SPA route.
  615. // URLs containing a "?" character won't be blacklisted as they're likely
  616. // a route with query params (e.g. auth callbacks).
  617. new RegExp('/[^/?]+\\.[^/]+$'),
  618. ],
  619. }),
  620. isEnvProduction && new CompressionPlugin({
  621. filename: '[path][base].gz[query]',
  622. algorithm: 'gzip',
  623. test: /\.(css|js)$/,
  624. threshold: 10240,
  625. minRatio: 0.8
  626. }),
  627. // TypeScript type checking
  628. useTypeScript &&
  629. new ForkTsCheckerWebpackPlugin({
  630. typescript: resolve.sync('typescript', {
  631. basedir: paths.appNodeModules,
  632. }),
  633. async: isEnvDevelopment,
  634. useTypescriptIncrementalApi: true,
  635. checkSyntacticErrors: true,
  636. resolveModuleNameModule: process.versions.pnp
  637. ? `${__dirname}/pnpTs.js`
  638. : undefined,
  639. resolveTypeReferenceDirectiveModule: process.versions.pnp
  640. ? `${__dirname}/pnpTs.js`
  641. : undefined,
  642. tsconfig: paths.appTsConfig,
  643. reportFiles: [
  644. '**',
  645. '!**/__tests__/**',
  646. '!**/?(*.)(spec|test).*',
  647. '!**/src/setupProxy.*',
  648. '!**/src/setupTests.*',
  649. ],
  650. silent: true,
  651. // The formatter is invoked directly in WebpackDevServerUtils during development
  652. formatter: isEnvProduction ? typescriptFormatter : undefined,
  653. }),
  654. ].filter(Boolean),
  655. // Some libraries import Node modules but don't use them in the browser.
  656. // Tell webpack to provide empty mocks for them so importing them works.
  657. node: {
  658. module: 'empty',
  659. dgram: 'empty',
  660. dns: 'mock',
  661. fs: 'empty',
  662. http2: 'empty',
  663. net: 'empty',
  664. tls: 'empty',
  665. child_process: 'empty',
  666. },
  667. // Turn off performance processing because we utilize
  668. // our own hints via the FileSizeReporter
  669. performance: false,
  670. };
  671. };