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