UNPKG

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