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