webpack.config.js 31 KB

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