webpack.config.js 30 KB

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