-
Notifications
You must be signed in to change notification settings - Fork 27.5k
/
Copy pathwebpack-config.ts
3191 lines (2979 loc) · 108 KB
/
webpack-config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React from 'react'
import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWebpackPlugin'
import chalk from 'next/dist/compiled/chalk'
import crypto from 'crypto'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import path from 'path'
import semver from 'next/dist/compiled/semver'
import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import {
DOT_NEXT_ALIAS,
PAGES_DIR_ALIAS,
ROOT_DIR_ALIAS,
APP_DIR_ALIAS,
WEBPACK_LAYERS,
RSC_ACTION_PROXY_ALIAS,
RSC_ACTION_CLIENT_WRAPPER_ALIAS,
RSC_ACTION_VALIDATE_ALIAS,
WEBPACK_RESOURCE_QUERIES,
} from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js'
import { isEdgeRuntime } from '../lib/is-edge-runtime'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_APP,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
MIDDLEWARE_REACT_LOADABLE_MANIFEST,
REACT_LOADABLE_MANIFEST,
SERVER_DIRECTORY,
COMPILER_NAMES,
CompilerNameValues,
} from '../shared/lib/constants'
import { execOnce } from '../shared/lib/utils'
import { NextConfigComplete } from '../server/config-shared'
import { finalizeEntrypoint } from './entries'
import * as Log from './output/log'
import { buildConfiguration } from './webpack/config'
import MiddlewarePlugin, {
getEdgePolyfilledModules,
handleWebpackExternalForEdgeRuntime,
} from './webpack/plugins/middleware-plugin'
import BuildManifestPlugin from './webpack/plugins/build-manifest-plugin'
import { JsConfigPathsPlugin } from './webpack/plugins/jsconfig-paths-plugin'
import { DropClientPage } from './webpack/plugins/next-drop-client-page-plugin'
import PagesManifestPlugin from './webpack/plugins/pages-manifest-plugin'
import { ProfilingPlugin } from './webpack/plugins/profiling-plugin'
import { ReactLoadablePlugin } from './webpack/plugins/react-loadable-plugin'
import { WellKnownErrorsPlugin } from './webpack/plugins/wellknown-errors-plugin'
import { regexLikeCss } from './webpack/config/blocks/css'
import { CopyFilePlugin } from './webpack/plugins/copy-file-plugin'
import { ClientReferenceManifestPlugin } from './webpack/plugins/flight-manifest-plugin'
import { FlightClientEntryPlugin } from './webpack/plugins/flight-client-entry-plugin'
import { NextTypesPlugin } from './webpack/plugins/next-types-plugin'
import type {
Feature,
SWC_TARGET_TRIPLE,
} from './webpack/plugins/telemetry-plugin'
import type { Span } from '../trace'
import type { MiddlewareMatcher } from './analysis/get-page-static-info'
import loadJsConfig from './load-jsconfig'
import { loadBindings } from './swc'
import { AppBuildManifestPlugin } from './webpack/plugins/app-build-manifest-plugin'
import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin'
import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin'
import { getSupportedBrowsers } from './utils'
type ExcludesFalse = <T>(x: T | false) => x is T
type ClientEntries = {
[key: string]: string | string[]
}
const EXTERNAL_PACKAGES =
require('../lib/server-external-packages.json') as string[]
const NEXT_PROJECT_ROOT = path.join(__dirname, '..', '..')
const NEXT_PROJECT_ROOT_DIST = path.join(NEXT_PROJECT_ROOT, 'dist')
const NEXT_PROJECT_ROOT_DIST_CLIENT = path.join(
NEXT_PROJECT_ROOT_DIST,
'client'
)
const isWebpackServerLayer = (layer: string | null) =>
Boolean(layer && WEBPACK_LAYERS.GROUP.server.includes(layer))
if (parseInt(React.version) < 18) {
throw new Error('Next.js requires react >= 18.2.0 to be installed.')
}
const babelIncludeRegexes: RegExp[] = [
/next[\\/]dist[\\/](esm[\\/])?shared[\\/]lib/,
/next[\\/]dist[\\/](esm[\\/])?client/,
/next[\\/]dist[\\/](esm[\\/])?pages/,
/[\\/](strip-ansi|ansi-regex|styled-jsx)[\\/]/,
]
const reactPackagesRegex = /^(react|react-dom|react-server-dom-webpack)($|\/)/
const asyncStoragesRegex =
/next[\\/]dist[\\/](esm[\\/])?client[\\/]components[\\/](static-generation-async-storage|action-async-storage|request-async-storage)/
// exports.<conditionName>
const edgeConditionNames = [
'edge-light',
'worker',
// inherits the default conditions
'...',
]
// packageJson.<mainField>
const mainFieldsPerCompiler: Record<CompilerNameValues, string[]> = {
[COMPILER_NAMES.server]: ['main', 'module'],
[COMPILER_NAMES.client]: ['browser', 'module', 'main'],
[COMPILER_NAMES.edgeServer]: [
'edge-light',
'worker',
// inherits the default conditions
'...',
],
}
const BABEL_CONFIG_FILES = [
'.babelrc',
'.babelrc.json',
'.babelrc.js',
'.babelrc.mjs',
'.babelrc.cjs',
'babel.config.js',
'babel.config.json',
'babel.config.mjs',
'babel.config.cjs',
]
export const getBabelConfigFile = async (dir: string) => {
const babelConfigFile = await BABEL_CONFIG_FILES.reduce(
async (memo: Promise<string | undefined>, filename) => {
const configFilePath = path.join(dir, filename)
return (
(await memo) ||
((await fileExists(configFilePath)) ? configFilePath : undefined)
)
},
Promise.resolve(undefined)
)
return babelConfigFile
}
// Support for NODE_PATH
const nodePathList = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter((p) => !!p)
const watchOptions = Object.freeze({
aggregateTimeout: 5,
ignored:
// Matches **/node_modules/**, **/.git/** and **/.next/**
/^((?:[^/]*(?:\/|$))*)(\.(git|next)|node_modules)(\/((?:[^/]*(?:\/|$))*)(?:$|\/))?/,
})
function isModuleCSS(module: { type: string }) {
return (
// mini-css-extract-plugin
module.type === `css/mini-extract` ||
// extract-css-chunks-webpack-plugin (old)
module.type === `css/extract-chunks` ||
// extract-css-chunks-webpack-plugin (new)
module.type === `css/extract-css-chunks`
)
}
function errorIfEnvConflicted(config: NextConfigComplete, key: string) {
const isPrivateKey = /^(?:NODE_.+)|^(?:__.+)$/i.test(key)
const hasNextRuntimeKey = key === 'NEXT_RUNTIME'
if (isPrivateKey || hasNextRuntimeKey) {
throw new Error(
`The key "${key}" under "env" in ${config.configFileName} is not allowed. https://nextjs.org/docs/messages/env-key-not-allowed`
)
}
}
function isResourceInPackages(
resource: string,
packageNames?: string[],
packageDirMapping?: Map<string, string>
) {
return packageNames?.some((p: string) =>
packageDirMapping && packageDirMapping.has(p)
? resource.startsWith(packageDirMapping.get(p)! + path.sep)
: resource.includes(
path.sep +
path.join('node_modules', p.replace(/\//g, path.sep)) +
path.sep
)
)
}
export function getDefineEnv({
dev,
config,
distDir,
isClient,
hasRewrites,
isNodeServer,
isEdgeServer,
middlewareMatchers,
clientRouterFilters,
previewModeId,
fetchCacheKeyPrefix,
allowedRevalidateHeaderKeys,
}: {
dev?: boolean
distDir: string
isClient?: boolean
hasRewrites?: boolean
isNodeServer?: boolean
isEdgeServer?: boolean
middlewareMatchers?: MiddlewareMatcher[]
config: NextConfigComplete
clientRouterFilters: Parameters<
typeof getBaseWebpackConfig
>[1]['clientRouterFilters']
previewModeId?: string
fetchCacheKeyPrefix?: string
allowedRevalidateHeaderKeys?: string[]
}) {
return {
// internal field to identify the plugin config
__NEXT_DEFINE_ENV: 'true',
...Object.keys(process.env).reduce(
(prev: { [key: string]: string }, key: string) => {
if (key.startsWith('NEXT_PUBLIC_')) {
prev[`process.env.${key}`] = JSON.stringify(process.env[key]!)
}
return prev
},
{}
),
...Object.keys(config.env).reduce((acc, key) => {
errorIfEnvConflicted(config, key)
return {
...acc,
[`process.env.${key}`]: JSON.stringify(config.env[key]),
}
}, {}),
...(!isEdgeServer
? {}
: {
EdgeRuntime: JSON.stringify(
/**
* Cloud providers can set this environment variable to allow users
* and library authors to have different implementations based on
* the runtime they are running with, if it's not using `edge-runtime`
*/
process.env.NEXT_EDGE_RUNTIME_PROVIDER || 'edge-runtime'
),
}),
'process.turbopack': JSON.stringify(false),
// TODO: enforce `NODE_ENV` on `process.env`, and add a test:
'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production'),
'process.env.NEXT_RUNTIME': JSON.stringify(
isEdgeServer ? 'edge' : isNodeServer ? 'nodejs' : undefined
),
'process.env.__NEXT_ACTIONS_DEPLOYMENT_ID': JSON.stringify(
config.experimental.useDeploymentIdServerActions
),
'process.env.NEXT_DEPLOYMENT_ID': JSON.stringify(
config.experimental.deploymentId
),
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX':
JSON.stringify(fetchCacheKeyPrefix),
'process.env.__NEXT_PREVIEW_MODE_ID': JSON.stringify(previewModeId),
'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS': JSON.stringify(
allowedRevalidateHeaderKeys
),
'process.env.__NEXT_MIDDLEWARE_MATCHERS': JSON.stringify(
middlewareMatchers || []
),
'process.env.__NEXT_MANUAL_CLIENT_BASE_PATH': JSON.stringify(
config.experimental.manualClientBasePath
),
'process.env.__NEXT_NEW_LINK_BEHAVIOR': JSON.stringify(
config.experimental.newNextLinkBehavior
),
'process.env.__NEXT_CLIENT_ROUTER_FILTER_ENABLED': JSON.stringify(
config.experimental.clientRouterFilter
),
'process.env.__NEXT_CLIENT_ROUTER_S_FILTER': JSON.stringify(
clientRouterFilters?.staticFilter
),
'process.env.__NEXT_CLIENT_ROUTER_D_FILTER': JSON.stringify(
clientRouterFilters?.dynamicFilter
),
'process.env.__NEXT_OPTIMISTIC_CLIENT_CACHE': JSON.stringify(
config.experimental.optimisticClientCache
),
'process.env.__NEXT_MIDDLEWARE_PREFETCH': JSON.stringify(
config.experimental.middlewarePrefetch
),
'process.env.__NEXT_CROSS_ORIGIN': JSON.stringify(config.crossOrigin),
'process.browser': JSON.stringify(isClient),
'process.env.__NEXT_TEST_MODE': JSON.stringify(
process.env.__NEXT_TEST_MODE
),
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
...(dev && (isClient || isEdgeServer)
? {
'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir),
}
: {}),
'process.env.__NEXT_TRAILING_SLASH': JSON.stringify(config.trailingSlash),
'process.env.__NEXT_BUILD_INDICATOR': JSON.stringify(
config.devIndicators.buildActivity
),
'process.env.__NEXT_BUILD_INDICATOR_POSITION': JSON.stringify(
config.devIndicators.buildActivityPosition
),
'process.env.__NEXT_STRICT_MODE': JSON.stringify(
config.reactStrictMode === null ? false : config.reactStrictMode
),
'process.env.__NEXT_STRICT_MODE_APP': JSON.stringify(
// When next.config.js does not have reactStrictMode enabling appDir will enable it.
config.reactStrictMode === null
? config.experimental.appDir
? true
: false
: config.reactStrictMode
),
'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify(
!dev && config.optimizeFonts
),
'process.env.__NEXT_OPTIMIZE_CSS': JSON.stringify(
config.experimental.optimizeCss && !dev
),
'process.env.__NEXT_SCRIPT_WORKERS': JSON.stringify(
config.experimental.nextScriptWorkers && !dev
),
'process.env.__NEXT_SCROLL_RESTORATION': JSON.stringify(
config.experimental.scrollRestoration
),
'process.env.__NEXT_IMAGE_OPTS': JSON.stringify({
deviceSizes: config.images.deviceSizes,
imageSizes: config.images.imageSizes,
path: config.images.path,
loader: config.images.loader,
dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,
unoptimized: config?.images?.unoptimized,
...(dev
? {
// pass domains in development to allow validating on the client
domains: config.images.domains,
remotePatterns: config.images?.remotePatterns,
output: config.output,
}
: {}),
}),
'process.env.__NEXT_ROUTER_BASEPATH': JSON.stringify(config.basePath),
'process.env.__NEXT_STRICT_NEXT_HEAD': JSON.stringify(
config.experimental.strictNextHead
),
'process.env.__NEXT_HAS_REWRITES': JSON.stringify(hasRewrites),
'process.env.__NEXT_CONFIG_OUTPUT': JSON.stringify(config.output),
'process.env.__NEXT_I18N_SUPPORT': JSON.stringify(!!config.i18n),
'process.env.__NEXT_I18N_DOMAINS': JSON.stringify(config.i18n?.domains),
'process.env.__NEXT_ANALYTICS_ID': JSON.stringify(config.analyticsId),
'process.env.__NEXT_NO_MIDDLEWARE_URL_NORMALIZE': JSON.stringify(
config.skipMiddlewareUrlNormalize
),
'process.env.__NEXT_EXTERNAL_MIDDLEWARE_REWRITE_RESOLVE': JSON.stringify(
config.experimental.externalMiddlewareRewritesResolve
),
'process.env.__NEXT_MANUAL_TRAILING_SLASH': JSON.stringify(
config.skipTrailingSlashRedirect
),
'process.env.__NEXT_HAS_WEB_VITALS_ATTRIBUTION': JSON.stringify(
config.experimental.webVitalsAttribution &&
config.experimental.webVitalsAttribution.length > 0
),
'process.env.__NEXT_WEB_VITALS_ATTRIBUTION': JSON.stringify(
config.experimental.webVitalsAttribution
),
'process.env.__NEXT_ASSET_PREFIX': JSON.stringify(config.assetPrefix),
...(isNodeServer || isEdgeServer
? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
// This is typically found in unmaintained modules from the
// pre-webpack era (common in server-side code)
'global.GENTLY': JSON.stringify(false),
}
: undefined),
// stub process.env with proxy to warn a missing value is
// being accessed in development mode
...(config.experimental.pageEnv && dev
? {
'process.env': `
new Proxy(${isNodeServer ? 'process.env' : '{}'}, {
get(target, prop) {
if (typeof target[prop] === 'undefined') {
console.warn(\`An environment variable (\${prop}) that was not provided in the environment was accessed.\nSee more info here: https://nextjs.org/docs/messages/missing-env-value\`)
}
return target[prop]
}
})
`,
}
: {}),
}
}
function getReactProfilingInProduction() {
return {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}
}
function createRSCAliases(
bundledReactChannel: string,
opts: {
reactProductionProfiling: boolean
reactSharedSubset: boolean
reactDomServerRenderingStub: boolean
reactServerCondition?: boolean
}
) {
const alias: Record<string, string> = {
react$: `next/dist/compiled/react${bundledReactChannel}`,
'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}`,
'react/jsx-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-runtime`,
'react/jsx-dev-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-dev-runtime`,
'react-dom/client$': `next/dist/compiled/react-dom${bundledReactChannel}/client`,
'react-dom/server$': `next/dist/compiled/react-dom${bundledReactChannel}/server`,
'react-dom/server.edge$': `next/dist/compiled/react-dom${bundledReactChannel}/server.edge`,
'react-dom/server.browser$': `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`,
'react-server-dom-webpack/client$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client`,
'react-server-dom-webpack/client.edge$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client.edge`,
'react-server-dom-webpack/server.edge$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.edge`,
'react-server-dom-webpack/server.node$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.node`,
}
if (opts.reactSharedSubset) {
alias[
'react$'
] = `next/dist/compiled/react${bundledReactChannel}/react.shared-subset`
}
// Use server rendering stub for RSC
// x-ref: https://github.com/facebook/react/pull/25436
if (opts.reactDomServerRenderingStub) {
alias[
'react-dom$'
] = `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub`
}
// Alias `server-only` and `client-only` modules to their server/client only, vendored versions.
// These aliases are necessary if the user doesn't have those two packages installed manually.
if (typeof opts.reactServerCondition !== 'undefined') {
if (opts.reactServerCondition) {
// Alias to the `react-server` exports.
alias['server-only$'] = 'next/dist/compiled/server-only/empty'
alias['client-only$'] = 'next/dist/compiled/client-only/error'
} else {
alias['server-only$'] = 'next/dist/compiled/server-only/index'
alias['client-only$'] = 'next/dist/compiled/client-only/index'
}
}
if (opts.reactProductionProfiling) {
alias[
'react-dom$'
] = `next/dist/compiled/react-dom${bundledReactChannel}/profiling`
alias[
'scheduler/tracing'
] = `next/dist/compiled/scheduler${bundledReactChannel}/tracing-profiling`
}
return alias
}
const devtoolRevertWarning = execOnce(
(devtool: webpack.Configuration['devtool']) => {
console.warn(
chalk.yellow.bold('Warning: ') +
chalk.bold(`Reverting webpack devtool to '${devtool}'.\n`) +
'Changing the webpack devtool in development mode will cause severe performance regressions.\n' +
'Read more: https://nextjs.org/docs/messages/improper-devtool'
)
}
)
let loggedSwcDisabled = false
let loggedIgnoredCompilerOptions = false
function getOptimizedAliases(): { [pkg: string]: string } {
const stubWindowFetch = path.join(__dirname, 'polyfills', 'fetch', 'index.js')
const stubObjectAssign = path.join(__dirname, 'polyfills', 'object-assign.js')
const shimAssign = path.join(__dirname, 'polyfills', 'object.assign')
return Object.assign(
{},
{
unfetch$: stubWindowFetch,
'isomorphic-unfetch$': stubWindowFetch,
'whatwg-fetch$': path.join(
__dirname,
'polyfills',
'fetch',
'whatwg-fetch.js'
),
},
{
'object-assign$': stubObjectAssign,
// Stub Package: object.assign
'object.assign/auto': path.join(shimAssign, 'auto.js'),
'object.assign/implementation': path.join(
shimAssign,
'implementation.js'
),
'object.assign$': path.join(shimAssign, 'index.js'),
'object.assign/polyfill': path.join(shimAssign, 'polyfill.js'),
'object.assign/shim': path.join(shimAssign, 'shim.js'),
// Replace: full URL polyfill with platform-based polyfill
url: require.resolve('next/dist/compiled/native-url'),
}
)
}
export function attachReactRefresh(
webpackConfig: webpack.Configuration,
targetLoader: webpack.RuleSetUseItem
) {
let injections = 0
const reactRefreshLoaderName =
'next/dist/compiled/@next/react-refresh-utils/dist/loader'
const reactRefreshLoader = require.resolve(reactRefreshLoaderName)
webpackConfig.module?.rules?.forEach((rule) => {
if (rule && typeof rule === 'object' && 'use' in rule) {
const curr = rule.use
// When the user has configured `defaultLoaders.babel` for a input file:
if (curr === targetLoader) {
++injections
rule.use = [reactRefreshLoader, curr as webpack.RuleSetUseItem]
} else if (
Array.isArray(curr) &&
curr.some((r) => r === targetLoader) &&
// Check if loader already exists:
!curr.some(
(r) => r === reactRefreshLoader || r === reactRefreshLoaderName
)
) {
++injections
const idx = curr.findIndex((r) => r === targetLoader)
// Clone to not mutate user input
rule.use = [...curr]
// inject / input: [other, babel] output: [other, refresh, babel]:
rule.use.splice(idx, 0, reactRefreshLoader)
}
}
})
if (injections) {
Log.info(
`automatically enabled Fast Refresh for ${injections} custom loader${
injections > 1 ? 's' : ''
}`
)
}
}
export const NODE_RESOLVE_OPTIONS = {
dependencyType: 'commonjs',
modules: ['node_modules'],
fallback: false,
exportsFields: ['exports'],
importsFields: ['imports'],
conditionNames: ['node', 'require'],
descriptionFiles: ['package.json'],
extensions: ['.js', '.json', '.node'],
enforceExtensions: false,
symlinks: true,
mainFields: ['main'],
mainFiles: ['index'],
roots: [],
fullySpecified: false,
preferRelative: false,
preferAbsolute: false,
restrictions: [],
}
export const NODE_BASE_RESOLVE_OPTIONS = {
...NODE_RESOLVE_OPTIONS,
alias: false,
}
export const NODE_ESM_RESOLVE_OPTIONS = {
...NODE_RESOLVE_OPTIONS,
alias: false,
dependencyType: 'esm',
conditionNames: ['node', 'import'],
fullySpecified: true,
}
export const NODE_BASE_ESM_RESOLVE_OPTIONS = {
...NODE_ESM_RESOLVE_OPTIONS,
alias: false,
}
export const nextImageLoaderRegex =
/\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i
export async function resolveExternal(
dir: string,
esmExternalsConfig: NextConfigComplete['experimental']['esmExternals'],
context: string,
request: string,
isEsmRequested: boolean,
hasAppDir: boolean,
getResolve: (
options: any
) => (
resolveContext: string,
resolveRequest: string
) => Promise<[string | null, boolean]>,
isLocalCallback?: (res: string) => any,
baseResolveCheck = true,
esmResolveOptions: any = NODE_ESM_RESOLVE_OPTIONS,
nodeResolveOptions: any = NODE_RESOLVE_OPTIONS,
baseEsmResolveOptions: any = NODE_BASE_ESM_RESOLVE_OPTIONS,
baseResolveOptions: any = NODE_BASE_RESOLVE_OPTIONS
) {
const esmExternals = !!esmExternalsConfig
const looseEsmExternals = esmExternalsConfig === 'loose'
let res: string | null = null
let isEsm: boolean = false
let preferEsmOptions =
esmExternals && isEsmRequested ? [true, false] : [false]
// Disable esm resolving for app/ and pages/ so for esm package using under pages/
// won't load react through esm loader
if (hasAppDir) {
preferEsmOptions = [false]
}
for (const preferEsm of preferEsmOptions) {
const resolve = getResolve(
preferEsm ? esmResolveOptions : nodeResolveOptions
)
// Resolve the import with the webpack provided context, this
// ensures we're resolving the correct version when multiple
// exist.
try {
;[res, isEsm] = await resolve(context, request)
} catch (err) {
res = null
}
if (!res) {
continue
}
// ESM externals can only be imported (and not required).
// Make an exception in loose mode.
if (!isEsmRequested && isEsm && !looseEsmExternals) {
continue
}
if (isLocalCallback) {
return { localRes: isLocalCallback(res) }
}
// Bundled Node.js code is relocated without its node_modules tree.
// This means we need to make sure its request resolves to the same
// package that'll be available at runtime. If it's not identical,
// we need to bundle the code (even if it _should_ be external).
if (baseResolveCheck) {
let baseRes: string | null
let baseIsEsm: boolean
try {
const baseResolve = getResolve(
isEsm ? baseEsmResolveOptions : baseResolveOptions
)
;[baseRes, baseIsEsm] = await baseResolve(dir, request)
} catch (err) {
baseRes = null
baseIsEsm = false
}
// Same as above: if the package, when required from the root,
// would be different from what the real resolution would use, we
// cannot externalize it.
// if request is pointing to a symlink it could point to the the same file,
// the resolver will resolve symlinks so this is handled
if (baseRes !== res || isEsm !== baseIsEsm) {
res = null
continue
}
}
break
}
return { res, isEsm }
}
export async function loadProjectInfo({
dir,
config,
dev,
}: {
dir: string
config: NextConfigComplete
dev: boolean
}) {
const { jsConfig, resolvedBaseUrl } = await loadJsConfig(dir, config)
const supportedBrowsers = await getSupportedBrowsers(dir, dev, config)
return {
jsConfig,
resolvedBaseUrl,
supportedBrowsers,
}
}
export default async function getBaseWebpackConfig(
dir: string,
{
buildId,
config,
compilerType,
dev = false,
entrypoints,
isDevFallback = false,
pagesDir,
reactProductionProfiling = false,
rewrites,
originalRewrites,
originalRedirects,
runWebpackSpan,
appDir,
middlewareMatchers,
noMangling = false,
jsConfig,
resolvedBaseUrl,
supportedBrowsers,
clientRouterFilters,
previewModeId,
fetchCacheKeyPrefix,
allowedRevalidateHeaderKeys,
}: {
buildId: string
config: NextConfigComplete
compilerType: CompilerNameValues
dev?: boolean
entrypoints: webpack.EntryObject
isDevFallback?: boolean
pagesDir?: string
reactProductionProfiling?: boolean
rewrites: CustomRoutes['rewrites']
originalRewrites: CustomRoutes['rewrites'] | undefined
originalRedirects: CustomRoutes['redirects'] | undefined
runWebpackSpan: Span
appDir?: string
middlewareMatchers?: MiddlewareMatcher[]
noMangling?: boolean
jsConfig: any
resolvedBaseUrl: string | undefined
supportedBrowsers: string[] | undefined
clientRouterFilters?: {
staticFilter: ReturnType<
import('../shared/lib/bloom-filter').BloomFilter['export']
>
dynamicFilter: ReturnType<
import('../shared/lib/bloom-filter').BloomFilter['export']
>
}
previewModeId?: string
fetchCacheKeyPrefix?: string
allowedRevalidateHeaderKeys?: string[]
}
): Promise<webpack.Configuration> {
const isClient = compilerType === COMPILER_NAMES.client
const isEdgeServer = compilerType === COMPILER_NAMES.edgeServer
const isNodeServer = compilerType === COMPILER_NAMES.server
const hasRewrites =
rewrites.beforeFiles.length > 0 ||
rewrites.afterFiles.length > 0 ||
rewrites.fallback.length > 0
const hasAppDir = !!config.experimental.appDir && !!appDir
const hasServerComponents = hasAppDir
const disableOptimizedLoading = true
const enableTypedRoutes = !!config.experimental.typedRoutes && hasAppDir
const useServerActions = !!config.experimental.serverActions && hasAppDir
const bundledReactChannel = useServerActions ? '-experimental' : ''
if (isClient) {
if (
// @ts-expect-error: experimental.runtime is deprecated
isEdgeRuntime(config.experimental.runtime)
) {
Log.warn(
'You are using `experimental.runtime` which was removed. Check https://nextjs.org/docs/api-routes/edge-api-routes on how to use edge runtime.'
)
}
}
const babelConfigFile = await getBabelConfigFile(dir)
const distDir = path.join(dir, config.distDir)
let useSWCLoader = !babelConfigFile || config.experimental.forceSwcTransforms
let SWCBinaryTarget: [Feature, boolean] | undefined = undefined
if (useSWCLoader) {
// TODO: we do not collect wasm target yet
const binaryTarget = require('./swc')?.getBinaryMetadata?.()
?.target as SWC_TARGET_TRIPLE
SWCBinaryTarget = binaryTarget
? [`swc/target/${binaryTarget}` as const, true]
: undefined
}
if (!loggedSwcDisabled && !useSWCLoader && babelConfigFile) {
Log.info(
`Disabled SWC as replacement for Babel because of custom Babel configuration "${path.relative(
dir,
babelConfigFile
)}" https://nextjs.org/docs/messages/swc-disabled`
)
loggedSwcDisabled = true
}
// eagerly load swc bindings instead of waiting for transform calls
if (!babelConfigFile && isClient) {
await loadBindings()
}
if (!loggedIgnoredCompilerOptions && !useSWCLoader && config.compiler) {
Log.info(
'`compiler` options in `next.config.js` will be ignored while using Babel https://nextjs.org/docs/messages/ignored-compiler-options'
)
loggedIgnoredCompilerOptions = true
}
const getBabelLoader = () => {
return {
loader: require.resolve('./babel/loader/index'),
options: {
configFile: babelConfigFile,
isServer: isNodeServer || isEdgeServer,
distDir,
pagesDir,
cwd: dir,
development: dev,
hasServerComponents,
hasReactRefresh: dev && isClient,
hasJsxRuntime: true,
},
}
}
let swcTraceProfilingInitialized = false
const getSwcLoader = (extraOptions?: any) => {
if (
config?.experimental?.swcTraceProfiling &&
!swcTraceProfilingInitialized
) {
// This will init subscribers once only in a single process lifecycle,
// even though it can be called multiple times.
// Subscriber need to be initialized _before_ any actual swc's call (transform, etcs)
// to collect correct trace spans when they are called.
swcTraceProfilingInitialized = true
require('./swc')?.initCustomTraceSubscriber?.(
path.join(distDir, `swc-trace-profile-${Date.now()}.json`)
)
}
return {
loader: 'next-swc-loader',
options: {
isServer: isNodeServer || isEdgeServer,
rootDir: dir,
pagesDir,
appDir,
hasReactRefresh: dev && isClient,
hasServerComponents: true,
fileReading: config.experimental.swcFileReading,
nextConfig: config,
jsConfig,
supportedBrowsers,
swcCacheDir: path.join(dir, config?.distDir ?? '.next', 'cache', 'swc'),
...extraOptions,
},
}
}
const defaultLoaders = {
babel: useSWCLoader ? getSwcLoader() : getBabelLoader(),
}
const swcLoaderForServerLayer = hasServerComponents
? useSWCLoader
? [getSwcLoader({ isServerLayer: true })]
: // When using Babel, we will have to add the SWC loader
// as an additional pass to handle RSC correctly.
// This will cause some performance overhead but
// acceptable as Babel will not be recommended.
[getSwcLoader({ isServerLayer: true }), getBabelLoader()]
: []
const swcLoaderForClientLayer = hasServerComponents
? useSWCLoader
? [getSwcLoader({ hasServerComponents, isServerLayer: false })]
: // When using Babel, we will have to add the SWC loader
// as an additional pass to handle RSC correctly.
// This will cause some performance overhead but
// acceptable as Babel will not be recommended.
[getSwcLoader({ isServerLayer: false }), getBabelLoader()]
: []
const swcLoaderForMiddlewareLayer = useSWCLoader
? getSwcLoader({ hasServerComponents: false })
: // When using Babel, we will have to use SWC to do the optimization
// for middleware to tree shake the unused default optimized imports like "next/server".
// This will cause some performance overhead but
// acceptable as Babel will not be recommended.
[getSwcLoader({ hasServerComponents: false }), getBabelLoader()]
// Loader for API routes needs to be differently configured as it shouldn't
// have RSC transpiler enabled, so syntax checks such as invalid imports won't
// be performed.
const loaderForAPIRoutes =
hasServerComponents && useSWCLoader
? {
loader: 'next-swc-loader',
options: {
...getSwcLoader().options,
hasServerComponents: false,
},
}
: defaultLoaders.babel
const pageExtensions = config.pageExtensions
const outputPath =
isNodeServer || isEdgeServer
? path.join(distDir, SERVER_DIRECTORY)
: distDir
const reactServerCondition = [
'react-server',
...(isEdgeServer ? edgeConditionNames : []),
// inherits the default conditions
'...',
]
const clientEntries = isClient
? ({
// Backwards compatibility
'main.js': [],
...(dev
? {
[CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]: require.resolve(
`next/dist/compiled/@next/react-refresh-utils/dist/runtime`
),
[CLIENT_STATIC_FILES_RUNTIME_AMP]:
`./` +
path
.relative(
dir,
path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'dev', 'amp-dev')
)
.replace(/\\/g, '/'),
}
: {}),
[CLIENT_STATIC_FILES_RUNTIME_MAIN]:
`./` +
path
.relative(
dir,
path.join(
NEXT_PROJECT_ROOT_DIST_CLIENT,
dev ? `next-dev.js` : 'next.js'
)
)
.replace(/\\/g, '/'),
...(hasAppDir
? {
[CLIENT_STATIC_FILES_RUNTIME_MAIN_APP]: dev
? [
require.resolve(
`next/dist/compiled/@next/react-refresh-utils/dist/runtime`
),
`./` +
path
.relative(
dir,
path.join(