@xfe-repo/web-app 1.0.0

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