webpack.config.js 31 KB

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