forked from vercel/next.js
-
Notifications
You must be signed in to change notification settings - Fork 11
/
webpack-config.ts
2245 lines (2087 loc) · 73.4 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 ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-utils/ReactRefreshWebpackPlugin'
import chalk from 'next/dist/compiled/chalk'
import crypto from 'crypto'
import { webpack } from 'next/dist/compiled/webpack/webpack'
import type { webpack5 } from 'next/dist/compiled/webpack/webpack'
import path, { join as pathJoin, relative as relativePath } from 'path'
import { escapeStringRegexp } from '../shared/lib/escape-regexp'
import {
DOT_NEXT_ALIAS,
NEXT_PROJECT_ROOT,
NEXT_PROJECT_ROOT_DIST_CLIENT,
PAGES_DIR_ALIAS,
VIEWS_DIR_ALIAS,
} from '../lib/constants'
import { fileExists } from '../lib/file-exists'
import { CustomRoutes } from '../lib/load-custom-routes.js'
import {
CLIENT_STATIC_FILES_RUNTIME_AMP,
CLIENT_STATIC_FILES_RUNTIME_MAIN,
CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT,
CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL,
CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH,
CLIENT_STATIC_FILES_RUNTIME_WEBPACK,
MIDDLEWARE_REACT_LOADABLE_MANIFEST,
REACT_LOADABLE_MANIFEST,
SERVERLESS_DIRECTORY,
SERVER_DIRECTORY,
} 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 { build as buildConfiguration } from './webpack/config'
import MiddlewarePlugin 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 { TraceEntryPointsPlugin } from './webpack/plugins/next-trace-entrypoints-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 { ServerlessPlugin } from './webpack/plugins/serverless-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 { FlightManifestPlugin } from './webpack/plugins/flight-manifest-plugin'
import {
Feature,
SWC_TARGET_TRIPLE,
TelemetryPlugin,
} from './webpack/plugins/telemetry-plugin'
import type { Span } from '../trace'
import { withoutRSCExtensions } from './utils'
import browserslist from 'next/dist/compiled/browserslist'
import loadJsConfig from './load-jsconfig'
import { getMiddlewareSourceMapPlugins } from './webpack/plugins/middleware-source-maps-plugin'
import { loadBindings } from './swc'
const watchOptions = Object.freeze({
aggregateTimeout: 5,
ignored: ['**/.git/**', '**/.next/**'],
})
function getSupportedBrowsers(
dir: string,
isDevelopment: boolean
): string[] | undefined {
let browsers: any
try {
browsers = browserslist.loadConfig({
path: dir,
env: isDevelopment ? 'development' : 'production',
})
} catch {}
return browsers
}
type ExcludesFalse = <T>(x: T | false) => x is T
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'),
}
)
}
type ClientEntries = {
[key: string]: string | string[]
}
export function attachReactRefresh(
webpackConfig: webpack.Configuration,
targetLoader: webpack.RuleSetUseItem
) {
let injections = 0
const reactRefreshLoaderName =
'next/dist/compiled/@next/react-refresh-utils/loader'
const reactRefreshLoader = require.resolve(reactRefreshLoaderName)
webpackConfig.module?.rules.forEach((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(
appDir: string,
esmExternalsConfig: NextConfigComplete['experimental']['esmExternals'],
context: string,
request: string,
isEsmRequested: 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]
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(appDir, 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 default async function getBaseWebpackConfig(
dir: string,
{
buildId,
config,
compilerType,
dev = false,
entrypoints,
hasReactRoot,
isDevFallback = false,
pagesDir,
reactProductionProfiling = false,
rewrites,
runWebpackSpan,
target = 'server',
viewsDir,
}: {
buildId: string
config: NextConfigComplete
compilerType: 'client' | 'server' | 'edge-server'
dev?: boolean
entrypoints: webpack5.EntryObject
hasReactRoot: boolean
isDevFallback?: boolean
pagesDir: string
reactProductionProfiling?: boolean
rewrites: CustomRoutes['rewrites']
runWebpackSpan: Span
target?: string
viewsDir?: string
}
): Promise<webpack.Configuration> {
const isClient = compilerType === 'client'
const isEdgeServer = compilerType === 'edge-server'
const isNodeServer = compilerType === 'server'
const { useTypeScript, jsConfig, resolvedBaseUrl } = await loadJsConfig(
dir,
config
)
const supportedBrowsers = await getSupportedBrowsers(dir, dev)
const hasRewrites =
rewrites.beforeFiles.length > 0 ||
rewrites.afterFiles.length > 0 ||
rewrites.fallback.length > 0
// Make sure `reactRoot` is enabled when React 18 or experimental is detected.
if (hasReactRoot) {
config.experimental.reactRoot = true
}
// Only inform during one of the builds
if (isClient && config.experimental.reactRoot && !hasReactRoot) {
// It's fine to only mention React 18 here as we don't recommend people to try experimental.
Log.warn('You have to use React 18 to use `experimental.reactRoot`.')
}
if (isClient && config.experimental.runtime && !hasReactRoot) {
throw new Error(
'`experimental.runtime` requires `experimental.reactRoot` to be enabled along with React 18.'
)
}
if (config.experimental.serverComponents && !hasReactRoot) {
throw new Error(
'`experimental.serverComponents` requires React 18 to be installed.'
)
}
const hasConcurrentFeatures = hasReactRoot
const hasServerComponents =
hasConcurrentFeatures && !!config.experimental.serverComponents
const disableOptimizedLoading = hasConcurrentFeatures
? true
: config.experimental.disableOptimizedLoading
if (isClient) {
if (config.experimental.runtime === 'edge') {
Log.warn(
'You are using the experimental Edge Runtime with `experimental.runtime`.'
)
}
if (config.experimental.runtime === 'nodejs') {
Log.warn(
'You are using the experimental Node.js Runtime with `experimental.runtime`.'
)
}
if (hasServerComponents) {
Log.warn(
'You have experimental React Server Components enabled. Continue at your own risk.'
)
}
}
const babelConfigFile = await [
'.babelrc',
'.babelrc.json',
'.babelrc.js',
'.babelrc.mjs',
'.babelrc.cjs',
'babel.config.js',
'babel.config.json',
'babel.config.mjs',
'babel.config.cjs',
].reduce(async (memo: Promise<string | undefined>, filename) => {
const configFilePath = path.join(dir, filename)
return (
(await memo) ||
((await fileExists(configFilePath)) ? configFilePath : undefined)
)
}, Promise.resolve(undefined))
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 getBabelOrSwcLoader = () => {
if (useSWCLoader && config?.experimental?.swcTraceProfiling) {
// 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.
require('./swc')?.initCustomTraceSubscriber?.(
path.join(distDir, `swc-trace-profile-${Date.now()}.json`)
)
}
return useSWCLoader
? {
loader: 'next-swc-loader',
options: {
isServer: isNodeServer || isEdgeServer,
pagesDir,
hasReactRefresh: dev && isClient,
fileReading: config.experimental.swcFileReading,
nextConfig: config,
jsConfig,
},
}
: {
loader: require.resolve('./babel/loader/index'),
options: {
configFile: babelConfigFile,
isServer: isNodeServer || isEdgeServer,
distDir,
pagesDir,
cwd: dir,
development: dev,
hasReactRefresh: dev && isClient,
hasJsxRuntime: true,
},
}
}
const defaultLoaders = {
babel: getBabelOrSwcLoader(),
}
const rawPageExtensions = hasServerComponents
? withoutRSCExtensions(config.pageExtensions)
: config.pageExtensions
const serverComponentsRegex = new RegExp(
`\\.server\\.(${rawPageExtensions.join('|')})$`
)
const babelIncludeRegexes: RegExp[] = [
/next[\\/]dist[\\/]shared[\\/]lib/,
/next[\\/]dist[\\/]client/,
/next[\\/]dist[\\/]pages/,
/[\\/](strip-ansi|ansi-regex)[\\/]/,
]
// Support for NODE_PATH
const nodePathList = (process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
.filter((p) => !!p)
// Intentionally not using isTargetLikeServerless helper
const isLikeServerless =
target === 'serverless' || target === 'experimental-serverless-trace'
const outputPath =
isNodeServer || isEdgeServer
? path.join(
distDir,
isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
)
: distDir
const clientEntries = isClient
? ({
// Backwards compatibility
'main.js': [],
...(dev
? {
[CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]: require.resolve(
`next/dist/compiled/@next/react-refresh-utils/runtime`
),
[CLIENT_STATIC_FILES_RUNTIME_AMP]:
`./` +
relativePath(
dir,
pathJoin(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, '/'),
...(config.experimental.viewsDir
? {
[CLIENT_STATIC_FILES_RUNTIME_MAIN_ROOT]:
`./` +
path
.relative(
dir,
path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'views-next.js')
)
.replace(/\\/g, '/'),
}
: {}),
} as ClientEntries)
: undefined
function getReactProfilingInProduction() {
if (reactProductionProfiling) {
return {
'react-dom$': 'react-dom/profiling',
'scheduler/tracing': 'scheduler/tracing-profiling',
}
}
}
// tell webpack where to look for _app and _document
// using aliases to allow falling back to the default
// version when removed or not present
const clientResolveRewrites = require.resolve(
'../shared/lib/router/utils/resolve-rewrites'
)
const customAppAliases: { [key: string]: string[] } = {}
const customErrorAlias: { [key: string]: string[] } = {}
const customDocumentAliases: { [key: string]: string[] } = {}
const customRootAliases: { [key: string]: string[] } = {}
if (dev) {
customAppAliases[`${PAGES_DIR_ALIAS}/_app`] = [
...rawPageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_app.${ext}`))
return prev
}, [] as string[]),
'next/dist/pages/_app.js',
]
customAppAliases[`${PAGES_DIR_ALIAS}/_app.server`] = [
...rawPageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_app.server.${ext}`))
return prev
}, [] as string[]),
'next/dist/pages/_app.server.js',
]
customAppAliases[`${PAGES_DIR_ALIAS}/_error`] = [
...config.pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_error.${ext}`))
return prev
}, [] as string[]),
'next/dist/pages/_error.js',
]
customDocumentAliases[`${PAGES_DIR_ALIAS}/_document`] = [
...config.pageExtensions.reduce((prev, ext) => {
prev.push(path.join(pagesDir, `_document.${ext}`))
return prev
}, [] as string[]),
`next/dist/pages/_document.js`,
]
}
const resolveConfig = {
// Disable .mjs for node_modules bundling
extensions: isNodeServer
? [
'.js',
'.mjs',
...(useTypeScript ? ['.tsx', '.ts'] : []),
'.jsx',
'.json',
'.wasm',
]
: [
'.mjs',
'.js',
...(useTypeScript ? ['.tsx', '.ts'] : []),
'.jsx',
'.json',
'.wasm',
],
modules: [
'node_modules',
...nodePathList, // Support for NODE_PATH environment variable
],
alias: {
next: NEXT_PROJECT_ROOT,
...customAppAliases,
...customErrorAlias,
...customDocumentAliases,
...customRootAliases,
[PAGES_DIR_ALIAS]: pagesDir,
...(viewsDir
? {
[VIEWS_DIR_ALIAS]: viewsDir,
}
: {}),
[DOT_NEXT_ALIAS]: distDir,
...(isClient || isEdgeServer ? getOptimizedAliases() : {}),
...getReactProfilingInProduction(),
...(isClient || isEdgeServer
? {
[clientResolveRewrites]: hasRewrites
? clientResolveRewrites
: // With webpack 5 an alias can be pointed to false to noop
false,
}
: {}),
setimmediate: 'next/dist/compiled/setimmediate',
},
...(isClient || isEdgeServer
? {
fallback: {
process: require.resolve('./polyfills/process'),
},
}
: undefined),
mainFields: isClient
? ['browser', 'module', 'main']
: isEdgeServer
? ['module', 'main']
: ['main', 'module'],
plugins: [],
}
const terserOptions: any = {
parse: {
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// The following two options are known to break valid JavaScript code
comparisons: false,
inline: 2, // https://github.com/vercel/next.js/issues/7178#issuecomment-493048965
},
mangle: { safari10: true },
output: {
ecma: 5,
safari10: true,
comments: false,
// Fixes usage of Emoji and certain Regex
ascii_only: true,
},
}
const isModuleCSS = (module: { type: string }): boolean => {
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`
)
}
// Packages which will be split into the 'framework' chunk.
// Only top-level packages are included, e.g. nested copies like
// 'node_modules/meow/node_modules/object-assign' are not included.
const topLevelFrameworkPaths: string[] = []
const visitedFrameworkPackages = new Set<string>()
// Adds package-paths of dependencies recursively
const addPackagePath = (packageName: string, relativeToPath: string) => {
try {
if (visitedFrameworkPackages.has(packageName)) {
return
}
visitedFrameworkPackages.add(packageName)
const packageJsonPath = require.resolve(`${packageName}/package.json`, {
paths: [relativeToPath],
})
// Include a trailing slash so that a `.startsWith(packagePath)` check avoids false positives
// when one package name starts with the full name of a different package.
// For example:
// "node_modules/react-slider".startsWith("node_modules/react") // true
// "node_modules/react-slider".startsWith("node_modules/react/") // false
const directory = path.join(packageJsonPath, '../')
// Returning from the function in case the directory has already been added and traversed
if (topLevelFrameworkPaths.includes(directory)) return
topLevelFrameworkPaths.push(directory)
const dependencies = require(packageJsonPath).dependencies || {}
for (const name of Object.keys(dependencies)) {
addPackagePath(name, directory)
}
} catch (_) {
// don't error on failing to resolve framework packages
}
}
for (const packageName of ['react', 'react-dom']) {
addPackagePath(packageName, dir)
}
const crossOrigin = config.crossOrigin
const looseEsmExternals = config.experimental?.esmExternals === 'loose'
async function handleExternals(
context: string,
request: string,
dependencyType: string,
getResolve: (
options: any
) => (
resolveContext: string,
resolveRequest: string
) => Promise<[string | null, boolean]>
) {
// We need to externalize internal requests for files intended to
// not be bundled.
const isLocal: boolean =
request.startsWith('.') ||
// Always check for unix-style path, as webpack sometimes
// normalizes as posix.
path.posix.isAbsolute(request) ||
// When on Windows, we also want to check for Windows-specific
// absolute paths.
(process.platform === 'win32' && path.win32.isAbsolute(request))
// make sure import "next" shows a warning when imported
// in pages/components
if (request === 'next') {
return `commonjs next/dist/lib/import-next-warning`
}
// Relative requires don't need custom resolution, because they
// are relative to requests we've already resolved here.
// Absolute requires (require('/foo')) are extremely uncommon, but
// also have no need for customization as they're already resolved.
if (!isLocal) {
if (/^(?:next$|react(?:$|\/))/.test(request)) {
return `commonjs ${request}`
}
const notExternalModules =
/^(?:private-next-pages\/|next\/(?:dist\/pages\/|(?:app|document|link|image|constants|dynamic)$)|string-hash$)/
if (notExternalModules.test(request)) {
return
}
}
// When in esm externals mode, and using import, we resolve with
// ESM resolving options.
const isEsmRequested = dependencyType === 'esm'
const isLocalCallback = (localRes: string) => {
// Makes sure dist/shared and dist/server are not bundled
// we need to process shared `router/router` and `dynamic`,
// so that the DefinePlugin can inject process.env values
const isNextExternal =
/next[/\\]dist[/\\](shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic))/.test(
localRes
)
if (isNextExternal) {
// Generate Next.js external import
const externalRequest = path.posix.join(
'next',
'dist',
path
.relative(
// Root of Next.js package:
path.join(__dirname, '..'),
localRes
)
// Windows path normalization
.replace(/\\/g, '/')
)
return `commonjs ${externalRequest}`
} else {
// We don't want to retry local requests
// with other preferEsm options
return
}
}
const resolveResult = await resolveExternal(
dir,
config.experimental.esmExternals,
context,
request,
isEsmRequested,
getResolve,
isLocal ? isLocalCallback : undefined
)
if ('localRes' in resolveResult) {
return resolveResult.localRes
}
const { res, isEsm } = resolveResult
// If the request cannot be resolved we need to have
// webpack "bundle" it so it surfaces the not found error.
if (!res) {
return
}
// ESM externals can only be imported (and not required).
// Make an exception in loose mode.
if (!isEsmRequested && isEsm && !looseEsmExternals) {
throw new Error(
`ESM packages (${request}) need to be imported. Use 'import' to reference the package instead. https://nextjs.org/docs/messages/import-esm-externals`
)
}
const externalType = isEsm ? 'module' : 'commonjs'
if (
res.match(/next[/\\]dist[/\\]shared[/\\](?!lib[/\\]router[/\\]router)/) ||
res.match(/next[/\\]dist[/\\]compiled[/\\].*\.[mc]?js$/)
) {
return `${externalType} ${request}`
}
// Default pages have to be transpiled
if (
res.match(/[/\\]next[/\\]dist[/\\]/) ||
// This is the @babel/plugin-transform-runtime "helpers: true" option
res.match(/node_modules[/\\]@babel[/\\]runtime[/\\]/)
) {
return
}
// Webpack itself has to be compiled because it doesn't always use module relative paths
if (
res.match(/node_modules[/\\]webpack/) ||
res.match(/node_modules[/\\]css-loader/)
) {
return
}
// Anything else that is standard JavaScript within `node_modules`
// can be externalized.
if (/node_modules[/\\].*\.[mc]?js$/.test(res)) {
return `${externalType} ${request}`
}
// Default behavior: bundle the code!
}
const codeCondition = {
test: /\.(tsx|ts|js|cjs|mjs|jsx)$/,
...(config.experimental.externalDir
? // Allowing importing TS/TSX files from outside of the root dir.
{}
: { include: [dir, ...babelIncludeRegexes] }),
exclude: (excludePath: string) => {
if (babelIncludeRegexes.some((r) => r.test(excludePath))) {
return false
}
return /node_modules/.test(excludePath)
},
}
const serverComponentCodeCondition = {
test: serverComponentsRegex,
include: [dir, /next[\\/]dist[\\/]pages/],
}
let webpackConfig: webpack.Configuration = {
parallelism: Number(process.env.NEXT_WEBPACK_PARALLELISM) || undefined,
externals:
isClient || isEdgeServer
? // make sure importing "next" is handled gracefully for client
// bundles in case a user imported types and it wasn't removed
// TODO: should we warn/error for this instead?
[
'next',
...(isEdgeServer
? [
{
'@builder.io/partytown': '{}',
'next/dist/compiled/etag': '{}',
'next/dist/compiled/chalk': '{}',
'react-dom': '{}',
},
]
: []),
]
: target !== 'serverless'
? [
({
context,
request,
dependencyType,
getResolve,
}: {
context: string
request: string
dependencyType: string
getResolve: (
options: any
) => (
resolveContext: string,
resolveRequest: string,
callback: (
err?: Error,
result?: string,
resolveData?: { descriptionFileData?: { type?: any } }
) => void
) => void
}) =>
handleExternals(context, request, dependencyType, (options) => {
const resolveFunction = getResolve(options)
return (resolveContext: string, requestToResolve: string) =>
new Promise((resolve, reject) => {
resolveFunction(
resolveContext,
requestToResolve,
(err, result, resolveData) => {
if (err) return reject(err)
if (!result) return resolve([null, false])
const isEsm = /\.js$/i.test(result)
? resolveData?.descriptionFileData?.type === 'module'
: /\.mjs$/i.test(result)
resolve([result, isEsm])
}
)
})
}),
]
: [
// When the 'serverless' target is used all node_modules will be compiled into the output bundles
// So that the 'serverless' bundles have 0 runtime dependencies
'next/dist/compiled/@ampproject/toolbox-optimizer', // except this one
// Mark this as external if not enabled so it doesn't cause a
// webpack error from being missing
...(config.experimental.optimizeCss ? [] : ['critters']),
],
optimization: {
// @ts-ignore: TODO remove ts-ignore when webpack 4 is removed
emitOnErrors: !dev,
checkWasmTypes: false,
nodeEnv: false,
...(hasServerComponents
? {