@authing/native-js-ui-components 4.4.0-alpha.8 → 4.4.2

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