webpack.config.js 31 KB

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