webpack.config.js 32 KB

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