webpack.config.js 32 KB

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