|
|
import React from 'react' |
|
|
import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWebpackPlugin' |
|
|
import { yellow, bold } from '../lib/picocolors' |
|
|
import crypto from 'crypto' |
|
|
import { webpack } from 'next/dist/compiled/webpack/webpack' |
|
|
import path from 'path' |
|
|
|
|
|
import { getDefineEnv } from './define-env' |
|
|
import { escapeStringRegexp } from '../shared/lib/escape-regexp' |
|
|
import { WEBPACK_LAYERS, WEBPACK_RESOURCE_QUERIES } from '../lib/constants' |
|
|
import type { WebpackLayerName } from '../lib/constants' |
|
|
import { |
|
|
isWebpackBundledLayer, |
|
|
isWebpackClientOnlyLayer, |
|
|
shouldUseReactServerCondition, |
|
|
isWebpackDefaultLayer, |
|
|
RSPACK_DEFAULT_LAYERS_REGEX, |
|
|
} from './utils' |
|
|
import type { CustomRoutes } from '../lib/load-custom-routes.js' |
|
|
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, |
|
|
} from '../shared/lib/constants' |
|
|
import type { CompilerNameValues } from '../shared/lib/constants' |
|
|
import { execOnce } from '../shared/lib/utils' |
|
|
import type { 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 as NextFlightClientEntryPlugin } from './webpack/plugins/flight-client-entry-plugin' |
|
|
import { RspackFlightClientEntryPlugin } from './webpack/plugins/rspack-flight-client-entry-plugin' |
|
|
import { NextTypesPlugin } from './webpack/plugins/next-types-plugin' |
|
|
import type { |
|
|
Feature, |
|
|
SWC_TARGET_TRIPLE, |
|
|
} from './webpack/plugins/telemetry-plugin/telemetry-plugin' |
|
|
import type { Span } from '../trace' |
|
|
import type { MiddlewareMatcher } from './analysis/get-page-static-info' |
|
|
import loadJsConfig, { |
|
|
type JsConfig, |
|
|
type ResolvedBaseUrl, |
|
|
} 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' |
|
|
import { MemoryWithGcCachePlugin } from './webpack/plugins/memory-with-gc-cache-plugin' |
|
|
import { getBabelConfigFile } from './get-babel-config-file' |
|
|
import { needsExperimentalReact } from '../lib/needs-experimental-react' |
|
|
import type { SWCLoaderOptions } from './webpack/loaders/next-swc-loader' |
|
|
import { isResourceInPackages, makeExternalHandler } from './handle-externals' |
|
|
import { |
|
|
getMainField, |
|
|
edgeConditionNames, |
|
|
} from './webpack-config-rules/resolve' |
|
|
import { OptionalPeerDependencyResolverPlugin } from './webpack/plugins/optional-peer-dependency-resolve-plugin' |
|
|
import { |
|
|
createWebpackAliases, |
|
|
createServerOnlyClientOnlyAliases, |
|
|
createVendoredReactAliases, |
|
|
createNextApiEsmAliases, |
|
|
createAppRouterApiAliases, |
|
|
} from './create-compiler-aliases' |
|
|
import { hasCustomExportOutput } from '../export/utils' |
|
|
import { CssChunkingPlugin } from './webpack/plugins/css-chunking-plugin' |
|
|
import { |
|
|
getBabelLoader, |
|
|
getReactCompilerLoader, |
|
|
} from './get-babel-loader-config' |
|
|
import { |
|
|
NEXT_PROJECT_ROOT, |
|
|
NEXT_PROJECT_ROOT_DIST_CLIENT, |
|
|
} from './next-dir-paths' |
|
|
import { getRspackCore, getRspackReactRefresh } from '../shared/lib/get-rspack' |
|
|
import { RspackProfilingPlugin } from './webpack/plugins/rspack-profiling-plugin' |
|
|
import getWebpackBundler from '../shared/lib/get-webpack-bundler' |
|
|
import type { NextBuildContext } from './build-context' |
|
|
|
|
|
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 DEFAULT_TRANSPILED_PACKAGES = |
|
|
require('../lib/default-transpiled-packages.json') as string[] |
|
|
|
|
|
if (parseInt(React.version) < 18) { |
|
|
throw new Error('Next.js requires react >= 18.2.0 to be installed.') |
|
|
} |
|
|
|
|
|
export const babelIncludeRegexes: RegExp[] = [ |
|
|
/next[\\/]dist[\\/](esm[\\/])?shared[\\/]lib/, |
|
|
/next[\\/]dist[\\/](esm[\\/])?client/, |
|
|
/next[\\/]dist[\\/](esm[\\/])?pages/, |
|
|
/[\\/](strip-ansi|ansi-regex|styled-jsx)[\\/]/, |
|
|
] |
|
|
|
|
|
const browserNonTranspileModules = [ |
|
|
|
|
|
|
|
|
|
|
|
/[\\/]node_modules[\\/]process[\\/]browser/, |
|
|
|
|
|
|
|
|
/[\\/]next[\\/]dist[\\/]compiled[\\/](react|react-dom|react-server-dom-webpack)(-experimental)?($|[\\/])/, |
|
|
] |
|
|
const precompileRegex = /[\\/]next[\\/]dist[\\/]compiled[\\/]/ |
|
|
|
|
|
const asyncStoragesRegex = |
|
|
/next[\\/]dist[\\/](esm[\\/])?server[\\/]app-render[\\/](work-async-storage|action-async-storage|dynamic-access-async-storage|work-unit-async-storage)/ |
|
|
|
|
|
|
|
|
const nodePathList = (process.env.NODE_PATH || '') |
|
|
.split(process.platform === 'win32' ? ';' : ':') |
|
|
.filter((p) => !!p) |
|
|
|
|
|
const baseWatchOptions: webpack.Configuration['watchOptions'] = Object.freeze({ |
|
|
aggregateTimeout: 5, |
|
|
ignored: |
|
|
|
|
|
/^((?:[^/]*(?:\/|$))*)(\.(git|next)|node_modules)(\/((?:[^/]*(?:\/|$))*)(?:$|\/))?/, |
|
|
}) |
|
|
|
|
|
function isModuleCSS(module: { type: string }) { |
|
|
return ( |
|
|
|
|
|
module.type === `css/mini-extract` || |
|
|
|
|
|
module.type === `css/extract-chunks` || |
|
|
|
|
|
module.type === `css/extract-css-chunks` |
|
|
) |
|
|
} |
|
|
|
|
|
const devtoolRevertWarning = execOnce( |
|
|
(devtool: webpack.Configuration['devtool']) => { |
|
|
console.warn( |
|
|
yellow(bold('Warning: ')) + |
|
|
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 |
|
|
const reactRefreshLoaderName = |
|
|
'next/dist/compiled/@next/react-refresh-utils/dist/loader' |
|
|
|
|
|
function getReactRefreshLoader() { |
|
|
return process.env.NEXT_RSPACK |
|
|
? getRspackReactRefresh().loader |
|
|
: require.resolve(reactRefreshLoaderName) |
|
|
} |
|
|
|
|
|
export function attachReactRefresh( |
|
|
webpackConfig: webpack.Configuration, |
|
|
targetLoader: webpack.RuleSetUseItem |
|
|
) { |
|
|
const reactRefreshLoader = getReactRefreshLoader() |
|
|
webpackConfig.module?.rules?.forEach((rule) => { |
|
|
if (rule && typeof rule === 'object' && 'use' in rule) { |
|
|
const curr = rule.use |
|
|
|
|
|
if (curr === targetLoader) { |
|
|
rule.use = [reactRefreshLoader, curr as webpack.RuleSetUseItem] |
|
|
} else if ( |
|
|
Array.isArray(curr) && |
|
|
curr.some((r) => r === targetLoader) && |
|
|
|
|
|
!curr.some( |
|
|
(r) => r === reactRefreshLoader || r === reactRefreshLoaderName |
|
|
) |
|
|
) { |
|
|
const idx = curr.findIndex((r) => r === targetLoader) |
|
|
|
|
|
rule.use = [...curr] |
|
|
|
|
|
|
|
|
rule.use.splice(idx, 0, reactRefreshLoader) |
|
|
} |
|
|
} |
|
|
}) |
|
|
} |
|
|
|
|
|
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 loadProjectInfo({ |
|
|
dir, |
|
|
config, |
|
|
dev, |
|
|
}: { |
|
|
dir: string |
|
|
config: NextConfigComplete |
|
|
dev: boolean |
|
|
}): Promise<{ |
|
|
jsConfig: JsConfig |
|
|
jsConfigPath?: string |
|
|
resolvedBaseUrl: ResolvedBaseUrl |
|
|
supportedBrowsers: string[] | undefined |
|
|
}> { |
|
|
const { jsConfig, jsConfigPath, resolvedBaseUrl } = await loadJsConfig( |
|
|
dir, |
|
|
config |
|
|
) |
|
|
const supportedBrowsers = getSupportedBrowsers(dir, dev) |
|
|
return { |
|
|
jsConfig, |
|
|
jsConfigPath, |
|
|
resolvedBaseUrl, |
|
|
supportedBrowsers, |
|
|
} |
|
|
} |
|
|
|
|
|
export function hasExternalOtelApiPackage(): boolean { |
|
|
try { |
|
|
require('@opentelemetry/api') as typeof import('@opentelemetry/api') |
|
|
return true |
|
|
} catch { |
|
|
return false |
|
|
} |
|
|
} |
|
|
|
|
|
const UNSAFE_CACHE_REGEX = /[\\/]pages[\\/][^\\/]+(?:$|\?|#)/ |
|
|
|
|
|
export function getCacheDirectories( |
|
|
configs: webpack.Configuration[] |
|
|
): Set<string> { |
|
|
return new Set( |
|
|
configs |
|
|
.map((cfg) => { |
|
|
if (typeof cfg.cache === 'object' && cfg.cache.type === 'filesystem') { |
|
|
return cfg.cache.cacheDirectory |
|
|
} |
|
|
return null |
|
|
}) |
|
|
.filter((dir) => dir != null) |
|
|
) |
|
|
} |
|
|
|
|
|
export default async function getBaseWebpackConfig( |
|
|
dir: string, |
|
|
{ |
|
|
buildId, |
|
|
encryptionKey, |
|
|
config, |
|
|
compilerType, |
|
|
dev = false, |
|
|
entrypoints, |
|
|
isDevFallback = false, |
|
|
pagesDir, |
|
|
reactProductionProfiling = false, |
|
|
rewrites, |
|
|
originalRewrites, |
|
|
originalRedirects, |
|
|
runWebpackSpan, |
|
|
appDir, |
|
|
middlewareMatchers, |
|
|
noMangling, |
|
|
jsConfig, |
|
|
jsConfigPath, |
|
|
resolvedBaseUrl, |
|
|
supportedBrowsers, |
|
|
clientRouterFilters, |
|
|
fetchCacheKeyPrefix, |
|
|
isCompileMode, |
|
|
previewProps, |
|
|
}: { |
|
|
previewProps: NonNullable<(typeof NextBuildContext)['previewProps']> |
|
|
isCompileMode?: boolean |
|
|
buildId: string |
|
|
encryptionKey: string |
|
|
config: NextConfigComplete |
|
|
compilerType: CompilerNameValues |
|
|
dev?: boolean |
|
|
entrypoints: webpack.EntryObject |
|
|
isDevFallback?: boolean |
|
|
pagesDir: string | undefined |
|
|
reactProductionProfiling?: boolean |
|
|
rewrites: CustomRoutes['rewrites'] |
|
|
originalRewrites: CustomRoutes['rewrites'] | undefined |
|
|
originalRedirects: CustomRoutes['redirects'] | undefined |
|
|
runWebpackSpan: Span |
|
|
appDir: string | undefined |
|
|
middlewareMatchers?: MiddlewareMatcher[] |
|
|
noMangling?: boolean |
|
|
jsConfig: any |
|
|
jsConfigPath?: string |
|
|
resolvedBaseUrl: ResolvedBaseUrl |
|
|
supportedBrowsers: string[] | undefined |
|
|
clientRouterFilters?: { |
|
|
staticFilter: ReturnType< |
|
|
import('../shared/lib/bloom-filter').BloomFilter['export'] |
|
|
> |
|
|
dynamicFilter: ReturnType< |
|
|
import('../shared/lib/bloom-filter').BloomFilter['export'] |
|
|
> |
|
|
} |
|
|
fetchCacheKeyPrefix?: string |
|
|
} |
|
|
): Promise<webpack.Configuration> { |
|
|
const bundler = getWebpackBundler() |
|
|
const isClient = compilerType === COMPILER_NAMES.client |
|
|
const isEdgeServer = compilerType === COMPILER_NAMES.edgeServer |
|
|
const isNodeServer = compilerType === COMPILER_NAMES.server |
|
|
|
|
|
const isRspack = Boolean(process.env.NEXT_RSPACK) |
|
|
|
|
|
const FlightClientEntryPlugin = |
|
|
isRspack && process.env.BUILTIN_FLIGHT_CLIENT_ENTRY_PLUGIN |
|
|
? RspackFlightClientEntryPlugin |
|
|
: NextFlightClientEntryPlugin |
|
|
|
|
|
|
|
|
const isNodeOrEdgeCompilation = isNodeServer || isEdgeServer |
|
|
|
|
|
const hasRewrites = |
|
|
rewrites.beforeFiles.length > 0 || |
|
|
rewrites.afterFiles.length > 0 || |
|
|
rewrites.fallback.length > 0 |
|
|
|
|
|
const hasAppDir = !!appDir |
|
|
const disableOptimizedLoading = true |
|
|
const enableTypedRoutes = !!config.experimental.typedRoutes && hasAppDir |
|
|
const bundledReactChannel = needsExperimentalReact(config) |
|
|
? '-experimental' |
|
|
: '' |
|
|
|
|
|
const babelConfigFile = getBabelConfigFile(dir) |
|
|
|
|
|
if (!dev && hasCustomExportOutput(config)) { |
|
|
config.distDir = '.next' |
|
|
} |
|
|
const distDir = path.join(dir, config.distDir) |
|
|
|
|
|
let useSWCLoader = !babelConfigFile || config.experimental.forceSwcTransforms |
|
|
let SWCBinaryTarget: [Feature, boolean] | undefined = undefined |
|
|
if (useSWCLoader) { |
|
|
|
|
|
const binaryTarget = ( |
|
|
require('./swc') as typeof import('./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 |
|
|
} |
|
|
|
|
|
|
|
|
if (!babelConfigFile && isClient) { |
|
|
await loadBindings(config.experimental.useWasmBinary) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
const finalTranspilePackages: string[] = ( |
|
|
config.transpilePackages || [] |
|
|
).concat(DEFAULT_TRANSPILED_PACKAGES) |
|
|
|
|
|
for (const pkg of config.experimental.optimizePackageImports || []) { |
|
|
if (!finalTranspilePackages.includes(pkg)) { |
|
|
finalTranspilePackages.push(pkg) |
|
|
} |
|
|
} |
|
|
|
|
|
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 excludeCache: Record<string, boolean> = {} |
|
|
function exclude(excludePath: string): boolean { |
|
|
const cached = excludeCache[excludePath] |
|
|
if (cached !== undefined) { |
|
|
return cached |
|
|
} |
|
|
|
|
|
const shouldExclude = |
|
|
excludePath.includes('node_modules') && |
|
|
!babelIncludeRegexes.some((r) => r.test(excludePath)) && |
|
|
!isResourceInPackages(excludePath, finalTranspilePackages) |
|
|
|
|
|
excludeCache[excludePath] = shouldExclude |
|
|
return shouldExclude |
|
|
} |
|
|
|
|
|
const shouldIncludeExternalDirs = |
|
|
config.experimental.externalDir || !!config.transpilePackages |
|
|
const codeCondition = { |
|
|
test: { or: [/\.(tsx|ts|js|cjs|mjs|jsx)$/, /__barrel_optimize__/] }, |
|
|
...(shouldIncludeExternalDirs |
|
|
? |
|
|
{} |
|
|
: { include: [dir, ...babelIncludeRegexes] }), |
|
|
exclude, |
|
|
} |
|
|
|
|
|
const babelLoader = getBabelLoader( |
|
|
useSWCLoader, |
|
|
babelConfigFile, |
|
|
isNodeOrEdgeCompilation, |
|
|
distDir, |
|
|
pagesDir, |
|
|
dir, |
|
|
(appDir || pagesDir)!, |
|
|
dev, |
|
|
isClient, |
|
|
config.experimental?.reactCompiler, |
|
|
codeCondition.exclude |
|
|
) |
|
|
|
|
|
const reactCompilerLoader = babelLoader |
|
|
? undefined |
|
|
: getReactCompilerLoader( |
|
|
config.experimental?.reactCompiler, |
|
|
dir, |
|
|
dev, |
|
|
isNodeOrEdgeCompilation, |
|
|
codeCondition.exclude |
|
|
) |
|
|
|
|
|
let swcTraceProfilingInitialized = false |
|
|
const getSwcLoader = (extraOptions: Partial<SWCLoaderOptions>) => { |
|
|
if ( |
|
|
config?.experimental?.swcTraceProfiling && |
|
|
!swcTraceProfilingInitialized |
|
|
) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
swcTraceProfilingInitialized = true |
|
|
;( |
|
|
require('./swc') as typeof import('./swc') |
|
|
)?.initCustomTraceSubscriber?.( |
|
|
path.join(distDir, `swc-trace-profile-${Date.now()}.json`) |
|
|
) |
|
|
} |
|
|
|
|
|
const useBuiltinSwcLoader = process.env.BUILTIN_SWC_LOADER |
|
|
if (isRspack && useBuiltinSwcLoader) { |
|
|
return { |
|
|
loader: 'builtin:next-swc-loader', |
|
|
options: { |
|
|
isServer: isNodeOrEdgeCompilation, |
|
|
rootDir: dir, |
|
|
pagesDir, |
|
|
appDir, |
|
|
hasReactRefresh: dev && isClient, |
|
|
transpilePackages: finalTranspilePackages, |
|
|
supportedBrowsers, |
|
|
swcCacheDir: path.join( |
|
|
dir, |
|
|
config?.distDir ?? '.next', |
|
|
'cache', |
|
|
'swc' |
|
|
), |
|
|
serverReferenceHashSalt: encryptionKey, |
|
|
|
|
|
|
|
|
pnp: Boolean(process.versions.pnp), |
|
|
optimizeServerReact: Boolean(config.experimental.optimizeServerReact), |
|
|
modularizeImports: config.modularizeImports, |
|
|
decorators: Boolean( |
|
|
jsConfig?.compilerOptions?.experimentalDecorators |
|
|
), |
|
|
emitDecoratorMetadata: Boolean( |
|
|
jsConfig?.compilerOptions?.emitDecoratorMetadata |
|
|
), |
|
|
regeneratorRuntimePath: require.resolve( |
|
|
'next/dist/compiled/regenerator-runtime' |
|
|
), |
|
|
|
|
|
...extraOptions, |
|
|
}, |
|
|
} |
|
|
} |
|
|
|
|
|
return { |
|
|
loader: 'next-swc-loader', |
|
|
options: { |
|
|
isServer: isNodeOrEdgeCompilation, |
|
|
compilerType, |
|
|
rootDir: dir, |
|
|
pagesDir, |
|
|
appDir, |
|
|
hasReactRefresh: dev && isClient, |
|
|
nextConfig: config, |
|
|
jsConfig, |
|
|
transpilePackages: finalTranspilePackages, |
|
|
supportedBrowsers, |
|
|
swcCacheDir: path.join(dir, config?.distDir ?? '.next', 'cache', 'swc'), |
|
|
serverReferenceHashSalt: encryptionKey, |
|
|
...extraOptions, |
|
|
} satisfies SWCLoaderOptions, |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
const swcServerLayerLoader = getSwcLoader({ |
|
|
serverComponents: true, |
|
|
bundleLayer: WEBPACK_LAYERS.reactServerComponents, |
|
|
esm: true, |
|
|
}) |
|
|
const swcSSRLayerLoader = getSwcLoader({ |
|
|
serverComponents: true, |
|
|
bundleLayer: WEBPACK_LAYERS.serverSideRendering, |
|
|
esm: true, |
|
|
}) |
|
|
const swcBrowserLayerLoader = getSwcLoader({ |
|
|
serverComponents: true, |
|
|
bundleLayer: WEBPACK_LAYERS.appPagesBrowser, |
|
|
esm: true, |
|
|
}) |
|
|
|
|
|
const swcDefaultLoader = getSwcLoader({ |
|
|
serverComponents: true, |
|
|
esm: false, |
|
|
}) |
|
|
|
|
|
const defaultLoaders = { |
|
|
babel: useSWCLoader ? swcDefaultLoader : babelLoader!, |
|
|
} |
|
|
|
|
|
const appServerLayerLoaders = hasAppDir |
|
|
? [ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
swcServerLayerLoader, |
|
|
babelLoader, |
|
|
reactCompilerLoader, |
|
|
].filter(Boolean) |
|
|
: [] |
|
|
|
|
|
const instrumentLayerLoaders = [ |
|
|
'next-flight-loader', |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
swcServerLayerLoader, |
|
|
babelLoader, |
|
|
].filter(Boolean) |
|
|
|
|
|
const middlewareLayerLoaders = [ |
|
|
'next-flight-loader', |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getSwcLoader({ |
|
|
serverComponents: true, |
|
|
bundleLayer: WEBPACK_LAYERS.middleware, |
|
|
}), |
|
|
babelLoader, |
|
|
].filter(Boolean) |
|
|
|
|
|
const reactRefreshLoaders = dev && isClient ? [getReactRefreshLoader()] : [] |
|
|
|
|
|
|
|
|
const createClientLayerLoader = ({ |
|
|
isBrowserLayer, |
|
|
reactRefresh, |
|
|
}: { |
|
|
isBrowserLayer: boolean |
|
|
reactRefresh: boolean |
|
|
}) => [ |
|
|
...(reactRefresh ? reactRefreshLoaders : []), |
|
|
{ |
|
|
|
|
|
|
|
|
loader: 'next-flight-client-module-loader', |
|
|
}, |
|
|
...(hasAppDir |
|
|
? [ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
isBrowserLayer ? swcBrowserLayerLoader : swcSSRLayerLoader, |
|
|
babelLoader, |
|
|
reactCompilerLoader, |
|
|
].filter(Boolean) |
|
|
: []), |
|
|
] |
|
|
|
|
|
const appBrowserLayerLoaders = createClientLayerLoader({ |
|
|
isBrowserLayer: true, |
|
|
|
|
|
reactRefresh: false, |
|
|
}) |
|
|
const appSSRLayerLoaders = createClientLayerLoader({ |
|
|
isBrowserLayer: false, |
|
|
reactRefresh: true, |
|
|
}) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const apiRoutesLayerLoaders = useSWCLoader |
|
|
? getSwcLoader({ |
|
|
serverComponents: false, |
|
|
bundleLayer: WEBPACK_LAYERS.apiNode, |
|
|
}) |
|
|
: defaultLoaders.babel |
|
|
|
|
|
const pageExtensions = config.pageExtensions |
|
|
|
|
|
const outputPath = isNodeOrEdgeCompilation |
|
|
? path.join(distDir, SERVER_DIRECTORY) |
|
|
: distDir |
|
|
|
|
|
const reactServerCondition = [ |
|
|
'react-server', |
|
|
...(isEdgeServer ? edgeConditionNames : []), |
|
|
|
|
|
'...', |
|
|
] |
|
|
|
|
|
const reactRefreshEntry = isRspack |
|
|
? getRspackReactRefresh().entry |
|
|
: require.resolve( |
|
|
`next/dist/compiled/@next/react-refresh-utils/dist/runtime` |
|
|
) |
|
|
|
|
|
const clientEntries = isClient |
|
|
? ({ |
|
|
|
|
|
'main.js': [], |
|
|
...(dev |
|
|
? { |
|
|
[CLIENT_STATIC_FILES_RUNTIME_REACT_REFRESH]: reactRefreshEntry, |
|
|
[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 |
|
|
? [ |
|
|
reactRefreshEntry, |
|
|
`./` + |
|
|
path |
|
|
.relative( |
|
|
dir, |
|
|
path.join( |
|
|
NEXT_PROJECT_ROOT_DIST_CLIENT, |
|
|
'app-next-dev.js' |
|
|
) |
|
|
) |
|
|
.replace(/\\/g, '/'), |
|
|
] |
|
|
: [ |
|
|
`./` + |
|
|
path |
|
|
.relative( |
|
|
dir, |
|
|
path.join( |
|
|
NEXT_PROJECT_ROOT_DIST_CLIENT, |
|
|
'app-next.js' |
|
|
) |
|
|
) |
|
|
.replace(/\\/g, '/'), |
|
|
], |
|
|
} |
|
|
: {}), |
|
|
} satisfies ClientEntries) |
|
|
: undefined |
|
|
|
|
|
const resolveConfig: webpack.Configuration['resolve'] = { |
|
|
|
|
|
extensions: ['.js', '.mjs', '.tsx', '.ts', '.jsx', '.json', '.wasm'], |
|
|
extensionAlias: config.experimental.extensionAlias, |
|
|
modules: [ |
|
|
'node_modules', |
|
|
...nodePathList, |
|
|
], |
|
|
alias: createWebpackAliases({ |
|
|
distDir, |
|
|
isClient, |
|
|
isEdgeServer, |
|
|
dev, |
|
|
config, |
|
|
pagesDir, |
|
|
appDir, |
|
|
dir, |
|
|
reactProductionProfiling, |
|
|
}), |
|
|
...(isClient |
|
|
? { |
|
|
fallback: { |
|
|
process: require.resolve('./polyfills/process'), |
|
|
}, |
|
|
} |
|
|
: undefined), |
|
|
|
|
|
mainFields: getMainField(compilerType, false), |
|
|
...(isEdgeServer && { |
|
|
conditionNames: edgeConditionNames, |
|
|
}), |
|
|
plugins: [ |
|
|
isNodeServer ? new OptionalPeerDependencyResolverPlugin() : undefined, |
|
|
].filter(Boolean) as webpack.ResolvePluginInstance[], |
|
|
...((isRspack && jsConfigPath |
|
|
? { |
|
|
|
|
|
restrictions: [/^(?!.*\.d\.ts$).*$/], |
|
|
tsConfig: { |
|
|
configFile: jsConfigPath, |
|
|
}, |
|
|
} |
|
|
: {}) as any), |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const nextFrameworkPaths: string[] = [] |
|
|
const topLevelFrameworkPaths: string[] = [] |
|
|
const visitedFrameworkPackages = new Set<string>() |
|
|
|
|
|
const addPackagePath = ( |
|
|
packageName: string, |
|
|
relativeToPath: string, |
|
|
paths: string[] |
|
|
) => { |
|
|
try { |
|
|
if (visitedFrameworkPackages.has(packageName)) { |
|
|
return |
|
|
} |
|
|
visitedFrameworkPackages.add(packageName) |
|
|
|
|
|
const packageJsonPath = require.resolve(`${packageName}/package.json`, { |
|
|
paths: [relativeToPath], |
|
|
}) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const directory = path.join(packageJsonPath, '../') |
|
|
|
|
|
|
|
|
if (paths.includes(directory)) return |
|
|
paths.push(directory) |
|
|
const dependencies = require(packageJsonPath).dependencies || {} |
|
|
for (const name of Object.keys(dependencies)) { |
|
|
addPackagePath(name, directory, paths) |
|
|
} |
|
|
} catch (_) { |
|
|
|
|
|
} |
|
|
} |
|
|
|
|
|
for (const packageName of [ |
|
|
'react', |
|
|
'react-dom', |
|
|
...(hasAppDir |
|
|
? [ |
|
|
`next/dist/compiled/react${bundledReactChannel}`, |
|
|
`next/dist/compiled/react-dom${bundledReactChannel}`, |
|
|
] |
|
|
: []), |
|
|
]) { |
|
|
addPackagePath(packageName, dir, topLevelFrameworkPaths) |
|
|
} |
|
|
addPackagePath('next', dir, nextFrameworkPaths) |
|
|
|
|
|
const crossOrigin = config.crossOrigin |
|
|
|
|
|
|
|
|
|
|
|
if (config.serverExternalPackages && finalTranspilePackages) { |
|
|
const externalPackageConflicts = finalTranspilePackages.filter((pkg) => |
|
|
config.serverExternalPackages?.includes(pkg) |
|
|
) |
|
|
if (externalPackageConflicts.length > 0) { |
|
|
throw new Error( |
|
|
`The packages specified in the 'transpilePackages' conflict with the 'serverExternalPackages': ${externalPackageConflicts.join( |
|
|
', ' |
|
|
)}` |
|
|
) |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
const optOutBundlingPackages = EXTERNAL_PACKAGES.concat( |
|
|
...(config.serverExternalPackages || []) |
|
|
).filter((pkg) => !finalTranspilePackages?.includes(pkg)) |
|
|
|
|
|
const optOutBundlingPackageRegex = new RegExp( |
|
|
`[/\\\\]node_modules[/\\\\](${optOutBundlingPackages |
|
|
.map((p) => p.replace(/\//g, '[/\\\\]')) |
|
|
.join('|')})[/\\\\]` |
|
|
) |
|
|
|
|
|
const transpilePackagesRegex = new RegExp( |
|
|
`[/\\\\]node_modules[/\\\\](${finalTranspilePackages |
|
|
?.map((p) => p.replace(/\//g, '[/\\\\]')) |
|
|
.join('|')})[/\\\\]` |
|
|
) |
|
|
|
|
|
const handleExternals = makeExternalHandler({ |
|
|
config, |
|
|
optOutBundlingPackageRegex, |
|
|
transpiledPackages: finalTranspilePackages, |
|
|
dir, |
|
|
}) |
|
|
|
|
|
const pageExtensionsRegex = new RegExp(`\\.(${pageExtensions.join('|')})$`) |
|
|
|
|
|
const aliasCodeConditionTest = [codeCondition.test, pageExtensionsRegex] |
|
|
|
|
|
const builtinModules = (require('module') as typeof import('module')) |
|
|
.builtinModules |
|
|
|
|
|
const shouldEnableSlowModuleDetection = |
|
|
!!config.experimental.slowModuleDetection && dev |
|
|
|
|
|
const getParallelism = () => { |
|
|
const override = Number(process.env.NEXT_WEBPACK_PARALLELISM) |
|
|
if (shouldEnableSlowModuleDetection) { |
|
|
if (override) { |
|
|
console.warn( |
|
|
'NEXT_WEBPACK_PARALLELISM is specified but will be ignored due to experimental.slowModuleDetection being enabled.' |
|
|
) |
|
|
} |
|
|
return 1 |
|
|
} |
|
|
return override || undefined |
|
|
} |
|
|
|
|
|
const telemetryPlugin = |
|
|
!dev && |
|
|
isClient && |
|
|
new ( |
|
|
require('./webpack/plugins/telemetry-plugin/telemetry-plugin') as typeof import('./webpack/plugins/telemetry-plugin/telemetry-plugin') |
|
|
).TelemetryPlugin( |
|
|
new Map( |
|
|
[ |
|
|
['swcLoader', useSWCLoader], |
|
|
['swcRelay', !!config.compiler?.relay], |
|
|
['swcStyledComponents', !!config.compiler?.styledComponents], |
|
|
[ |
|
|
'swcReactRemoveProperties', |
|
|
!!config.compiler?.reactRemoveProperties, |
|
|
], |
|
|
[ |
|
|
'swcExperimentalDecorators', |
|
|
!!jsConfig?.compilerOptions?.experimentalDecorators, |
|
|
], |
|
|
['swcRemoveConsole', !!config.compiler?.removeConsole], |
|
|
['swcImportSource', !!jsConfig?.compilerOptions?.jsxImportSource], |
|
|
['swcEmotion', !!config.compiler?.emotion], |
|
|
['transpilePackages', !!config.transpilePackages], |
|
|
['skipMiddlewareUrlNormalize', !!config.skipMiddlewareUrlNormalize], |
|
|
['skipTrailingSlashRedirect', !!config.skipTrailingSlashRedirect], |
|
|
['modularizeImports', !!config.modularizeImports], |
|
|
|
|
|
['esmExternals', config.experimental.esmExternals !== true], |
|
|
SWCBinaryTarget, |
|
|
].filter<[Feature, boolean]>(Boolean as any) |
|
|
) |
|
|
) |
|
|
|
|
|
let webpackConfig: webpack.Configuration = { |
|
|
parallelism: getParallelism(), |
|
|
...(isNodeServer ? { externalsPresets: { node: true } } : {}), |
|
|
|
|
|
externals: |
|
|
isClient || isEdgeServer |
|
|
? |
|
|
|
|
|
|
|
|
[ |
|
|
'next', |
|
|
...(isEdgeServer |
|
|
? [ |
|
|
{ |
|
|
'@builder.io/partytown': '{}', |
|
|
'next/dist/compiled/etag': '{}', |
|
|
}, |
|
|
getEdgePolyfilledModules(), |
|
|
handleWebpackExternalForEdgeRuntime, |
|
|
] |
|
|
: []), |
|
|
] |
|
|
: [ |
|
|
...builtinModules, |
|
|
({ |
|
|
context, |
|
|
request, |
|
|
dependencyType, |
|
|
contextInfo, |
|
|
getResolve, |
|
|
}: { |
|
|
context: string |
|
|
request: string |
|
|
dependencyType: string |
|
|
contextInfo: { |
|
|
issuer: string |
|
|
issuerLayer: string | null |
|
|
compiler: string |
|
|
} |
|
|
getResolve: ( |
|
|
options: any |
|
|
) => ( |
|
|
resolveContext: string, |
|
|
resolveRequest: string, |
|
|
callback: ( |
|
|
err?: Error, |
|
|
result?: string, |
|
|
resolveData?: { descriptionFileData?: { type?: any } } |
|
|
) => void |
|
|
) => void |
|
|
}) => |
|
|
handleExternals( |
|
|
context, |
|
|
request, |
|
|
dependencyType, |
|
|
contextInfo.issuerLayer as WebpackLayerName, |
|
|
(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]) |
|
|
} |
|
|
) |
|
|
}) |
|
|
} |
|
|
), |
|
|
], |
|
|
|
|
|
optimization: { |
|
|
emitOnErrors: !dev, |
|
|
checkWasmTypes: false, |
|
|
nodeEnv: false, |
|
|
|
|
|
splitChunks: ((): |
|
|
| Required<webpack.Configuration>['optimization']['splitChunks'] |
|
|
| false => { |
|
|
|
|
|
if (dev) { |
|
|
if (isNodeServer) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const extractRootNodeModule = (modulePath: string) => { |
|
|
|
|
|
|
|
|
const regex = |
|
|
/node_modules(?:\/|\\)\.?(?:pnpm(?:\/|\\))?([^/\\]+)/ |
|
|
const match = modulePath.match(regex) |
|
|
return match ? match[1] : null |
|
|
} |
|
|
return { |
|
|
cacheGroups: { |
|
|
|
|
|
|
|
|
vendor: { |
|
|
chunks: 'all', |
|
|
reuseExistingChunk: true, |
|
|
test: /[\\/]node_modules[\\/]/, |
|
|
minSize: 0, |
|
|
minChunks: 1, |
|
|
maxAsyncRequests: 300, |
|
|
maxInitialRequests: 300, |
|
|
name: (module: webpack.Module) => { |
|
|
const moduleId = module.nameForCondition()! |
|
|
const rootModule = extractRootNodeModule(moduleId) |
|
|
if (rootModule) { |
|
|
return `vendor-chunks/${rootModule}` |
|
|
} else { |
|
|
const hash = crypto.createHash('sha1').update(moduleId) |
|
|
hash.update(moduleId) |
|
|
return `vendor-chunks/${hash.digest('hex')}` |
|
|
} |
|
|
}, |
|
|
}, |
|
|
|
|
|
default: false, |
|
|
defaultVendors: false, |
|
|
}, |
|
|
} |
|
|
} |
|
|
|
|
|
return false |
|
|
} |
|
|
|
|
|
if (isNodeServer || isEdgeServer) { |
|
|
return { |
|
|
filename: `${isEdgeServer ? `edge-chunks/` : ''}[name].js`, |
|
|
chunks: 'all', |
|
|
minChunks: 2, |
|
|
} |
|
|
} |
|
|
|
|
|
const frameworkCacheGroup = { |
|
|
chunks: 'all' as const, |
|
|
name: 'framework', |
|
|
|
|
|
layer: isWebpackDefaultLayer, |
|
|
test(module: any) { |
|
|
const resource = module.nameForCondition?.() |
|
|
return resource |
|
|
? topLevelFrameworkPaths.some((pkgPath) => |
|
|
resource.startsWith(pkgPath) |
|
|
) |
|
|
: false |
|
|
}, |
|
|
priority: 40, |
|
|
|
|
|
|
|
|
enforce: true, |
|
|
} |
|
|
|
|
|
const libCacheGroup = { |
|
|
test(module: { |
|
|
type: string |
|
|
size: Function |
|
|
nameForCondition: Function |
|
|
}): boolean { |
|
|
return ( |
|
|
!module.type?.startsWith('css') && |
|
|
module.size() > 160000 && |
|
|
/node_modules[/\\]/.test(module.nameForCondition() || '') |
|
|
) |
|
|
}, |
|
|
name(module: { |
|
|
layer: string | null | undefined |
|
|
type: string |
|
|
libIdent?: Function |
|
|
updateHash: (hash: crypto.Hash) => void |
|
|
}): string { |
|
|
const hash = crypto.createHash('sha1') |
|
|
if (isModuleCSS(module)) { |
|
|
module.updateHash(hash) |
|
|
} else { |
|
|
if (!module.libIdent) { |
|
|
throw new Error( |
|
|
`Encountered unknown module type: ${module.type}. Please open an issue.` |
|
|
) |
|
|
} |
|
|
hash.update(module.libIdent({ context: dir })) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (module.layer) { |
|
|
hash.update(module.layer) |
|
|
} |
|
|
|
|
|
return hash.digest('hex').substring(0, 8) |
|
|
}, |
|
|
priority: 30, |
|
|
minChunks: 1, |
|
|
reuseExistingChunk: true, |
|
|
} |
|
|
|
|
|
|
|
|
return { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
chunks: isRspack |
|
|
? |
|
|
|
|
|
/(?!polyfills|main|pages\/_app)/ |
|
|
: (chunk: any) => |
|
|
!/^(polyfills|main|pages\/_app)$/.test(chunk.name), |
|
|
|
|
|
cacheGroups: isRspack |
|
|
? { |
|
|
framework: { |
|
|
chunks: 'all' as const, |
|
|
name: 'framework', |
|
|
layer: RSPACK_DEFAULT_LAYERS_REGEX, |
|
|
test: /[/]node_modules[/](react|react-dom|next[/]dist[/]compiled[/](react|react-dom)(-experimental)?)[/]/, |
|
|
priority: 40, |
|
|
enforce: true, |
|
|
}, |
|
|
lib: { |
|
|
test: /[/]node_modules[/](?!.*\.(css|scss|sass|less|styl)$)/, |
|
|
name: 'lib', |
|
|
chunks: 'all', |
|
|
priority: 30, |
|
|
minChunks: 1, |
|
|
reuseExistingChunk: true, |
|
|
}, |
|
|
} |
|
|
: { |
|
|
framework: frameworkCacheGroup, |
|
|
lib: libCacheGroup, |
|
|
}, |
|
|
maxInitialRequests: 25, |
|
|
minSize: 20000, |
|
|
} |
|
|
})(), |
|
|
runtimeChunk: isClient |
|
|
? { name: CLIENT_STATIC_FILES_RUNTIME_WEBPACK } |
|
|
: undefined, |
|
|
|
|
|
minimize: |
|
|
!dev && |
|
|
(isClient || |
|
|
isEdgeServer || |
|
|
(isNodeServer && config.experimental.serverMinification)), |
|
|
minimizer: [ |
|
|
|
|
|
isRspack |
|
|
? new (getRspackCore().SwcJsMinimizerRspackPlugin)({ |
|
|
|
|
|
|
|
|
minimizerOptions: { |
|
|
compress: { |
|
|
inline: 2, |
|
|
global_defs: { |
|
|
'process.env.__NEXT_PRIVATE_MINIMIZE_MACRO_FALSE': false, |
|
|
}, |
|
|
}, |
|
|
mangle: !noMangling && { |
|
|
reserved: ['AbortSignal'], |
|
|
disableCharFreq: !isClient, |
|
|
}, |
|
|
}, |
|
|
}) |
|
|
: (compiler: webpack.Compiler) => { |
|
|
|
|
|
const { MinifyPlugin } = |
|
|
require('./webpack/plugins/minify-webpack-plugin/src') as typeof import('./webpack/plugins/minify-webpack-plugin/src') |
|
|
new MinifyPlugin({ |
|
|
noMangling, |
|
|
disableCharFreq: !isClient, |
|
|
}).apply(compiler) |
|
|
}, |
|
|
|
|
|
|
|
|
|
|
|
isRspack && |
|
|
(process.env.__NEXT_TEST_MODE |
|
|
? config.experimental.useLightningcss |
|
|
: config.experimental?.useLightningcss === undefined || |
|
|
config.experimental.useLightningcss) |
|
|
? new (getRspackCore().LightningCssMinimizerRspackPlugin)({ |
|
|
|
|
|
minimizerOptions: { |
|
|
targets: supportedBrowsers, |
|
|
}, |
|
|
}) |
|
|
: (compiler: webpack.Compiler) => { |
|
|
const { CssMinimizerPlugin } = |
|
|
require('./webpack/plugins/css-minimizer-plugin') as typeof import('./webpack/plugins/css-minimizer-plugin') |
|
|
new CssMinimizerPlugin({ |
|
|
postcssOptions: { |
|
|
map: { |
|
|
|
|
|
|
|
|
inline: false, |
|
|
|
|
|
|
|
|
annotation: false, |
|
|
}, |
|
|
}, |
|
|
}).apply(compiler) |
|
|
}, |
|
|
], |
|
|
}, |
|
|
context: dir, |
|
|
|
|
|
entry: async () => { |
|
|
return { |
|
|
...(clientEntries ? clientEntries : {}), |
|
|
...entrypoints, |
|
|
} |
|
|
}, |
|
|
watchOptions: Object.freeze({ |
|
|
...baseWatchOptions, |
|
|
poll: config.watchOptions?.pollIntervalMs, |
|
|
}), |
|
|
output: { |
|
|
|
|
|
|
|
|
publicPath: `${ |
|
|
config.assetPrefix |
|
|
? config.assetPrefix.endsWith('/') |
|
|
? config.assetPrefix.slice(0, -1) |
|
|
: config.assetPrefix |
|
|
: '' |
|
|
}/_next/`, |
|
|
path: !dev && isNodeServer ? path.join(outputPath, 'chunks') : outputPath, |
|
|
|
|
|
filename: isNodeOrEdgeCompilation |
|
|
? dev || isEdgeServer |
|
|
? `[name].js` |
|
|
: `../[name].js` |
|
|
: `static/chunks/${isDevFallback ? 'fallback/' : ''}[name]${ |
|
|
dev ? '' : '-[contenthash]' |
|
|
}.js`, |
|
|
library: isClient || isEdgeServer ? '_N_E' : undefined, |
|
|
libraryTarget: isClient || isEdgeServer ? 'assign' : 'commonjs2', |
|
|
hotUpdateChunkFilename: 'static/webpack/[id].[fullhash].hot-update.js', |
|
|
hotUpdateMainFilename: |
|
|
'static/webpack/[fullhash].[runtime].hot-update.json', |
|
|
|
|
|
chunkFilename: isNodeOrEdgeCompilation |
|
|
? '[name].js' |
|
|
: `static/chunks/${isDevFallback ? 'fallback/' : ''}${ |
|
|
dev ? '[name]' : '[name].[contenthash]' |
|
|
}.js`, |
|
|
strictModuleExceptionHandling: true, |
|
|
crossOriginLoading: crossOrigin, |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
devtoolModuleFilenameTemplate: dev |
|
|
? '[absolute-resource-path]' |
|
|
: undefined, |
|
|
webassemblyModuleFilename: 'static/wasm/[modulehash].wasm', |
|
|
hashFunction: 'xxhash64', |
|
|
hashDigestLength: 16, |
|
|
}, |
|
|
performance: false, |
|
|
resolve: resolveConfig, |
|
|
resolveLoader: { |
|
|
|
|
|
alias: [ |
|
|
'error-loader', |
|
|
'next-swc-loader', |
|
|
'next-client-pages-loader', |
|
|
'next-image-loader', |
|
|
'next-metadata-image-loader', |
|
|
'next-style-loader', |
|
|
'next-flight-loader', |
|
|
'next-flight-client-entry-loader', |
|
|
'next-flight-action-entry-loader', |
|
|
'next-flight-client-module-loader', |
|
|
'next-flight-server-reference-proxy-loader', |
|
|
'empty-loader', |
|
|
'next-middleware-loader', |
|
|
'next-edge-function-loader', |
|
|
'next-edge-app-route-loader', |
|
|
'next-edge-ssr-loader', |
|
|
'next-middleware-asset-loader', |
|
|
'next-middleware-wasm-loader', |
|
|
'next-app-loader', |
|
|
'next-route-loader', |
|
|
'next-font-loader', |
|
|
'next-invalid-import-error-loader', |
|
|
'next-metadata-route-loader', |
|
|
'modularize-import-loader', |
|
|
'next-barrel-loader', |
|
|
'next-error-browser-binary-loader', |
|
|
].reduce( |
|
|
(alias, loader) => { |
|
|
|
|
|
alias[loader] = path.join(__dirname, 'webpack', 'loaders', loader) |
|
|
|
|
|
return alias |
|
|
}, |
|
|
{} as Record<string, string> |
|
|
), |
|
|
modules: [ |
|
|
'node_modules', |
|
|
...nodePathList, |
|
|
], |
|
|
plugins: [], |
|
|
}, |
|
|
module: { |
|
|
rules: [ |
|
|
|
|
|
{ |
|
|
issuerLayer: { |
|
|
or: [ |
|
|
...WEBPACK_LAYERS.GROUP.serverOnly, |
|
|
...WEBPACK_LAYERS.GROUP.neutralTarget, |
|
|
], |
|
|
}, |
|
|
resolve: { |
|
|
|
|
|
alias: createServerOnlyClientOnlyAliases(true), |
|
|
}, |
|
|
}, |
|
|
{ |
|
|
issuerLayer: { |
|
|
not: [ |
|
|
...WEBPACK_LAYERS.GROUP.serverOnly, |
|
|
...WEBPACK_LAYERS.GROUP.neutralTarget, |
|
|
], |
|
|
}, |
|
|
resolve: { |
|
|
|
|
|
alias: createServerOnlyClientOnlyAliases(false), |
|
|
}, |
|
|
}, |
|
|
|
|
|
{ |
|
|
test: [ |
|
|
/^client-only$/, |
|
|
/next[\\/]dist[\\/]compiled[\\/]client-only[\\/]error/, |
|
|
], |
|
|
loader: 'next-invalid-import-error-loader', |
|
|
issuerLayer: { |
|
|
or: WEBPACK_LAYERS.GROUP.serverOnly, |
|
|
}, |
|
|
options: { |
|
|
message: |
|
|
"'client-only' cannot be imported from a Server Component module. It should only be used from a Client Component.", |
|
|
}, |
|
|
}, |
|
|
{ |
|
|
test: [ |
|
|
/^server-only$/, |
|
|
/next[\\/]dist[\\/]compiled[\\/]server-only[\\/]index/, |
|
|
], |
|
|
loader: 'next-invalid-import-error-loader', |
|
|
issuerLayer: { |
|
|
not: [ |
|
|
...WEBPACK_LAYERS.GROUP.serverOnly, |
|
|
...WEBPACK_LAYERS.GROUP.neutralTarget, |
|
|
], |
|
|
}, |
|
|
options: { |
|
|
message: |
|
|
"'server-only' cannot be imported from a Client Component module. It should only be used from a Server Component.", |
|
|
}, |
|
|
}, |
|
|
|
|
|
|
|
|
|
|
|
{ |
|
|
test: [ |
|
|
/^client-only$/, |
|
|
/next[\\/]dist[\\/]compiled[\\/]client-only[\\/]error/, |
|
|
], |
|
|
loader: 'empty-loader', |
|
|
issuerLayer: { |
|
|
or: WEBPACK_LAYERS.GROUP.neutralTarget, |
|
|
}, |
|
|
}, |
|
|
...(isNodeServer |
|
|
? [] |
|
|
: [ |
|
|
{ |
|
|
test: /[\\/].*?\.node$/, |
|
|
loader: 'next-error-browser-binary-loader', |
|
|
}, |
|
|
]), |
|
|
...(hasAppDir |
|
|
? [ |
|
|
{ |
|
|
|
|
|
|
|
|
layer: WEBPACK_LAYERS.shared, |
|
|
test: asyncStoragesRegex, |
|
|
}, |
|
|
|
|
|
{ |
|
|
resourceQuery: new RegExp( |
|
|
WEBPACK_RESOURCE_QUERIES.metadataRoute |
|
|
), |
|
|
layer: WEBPACK_LAYERS.reactServerComponents, |
|
|
}, |
|
|
{ |
|
|
|
|
|
|
|
|
layer: WEBPACK_LAYERS.serverSideRendering, |
|
|
test: /next[\\/]dist[\\/](esm[\\/])?server[\\/]route-modules[\\/]app-page[\\/]module/, |
|
|
}, |
|
|
{ |
|
|
issuerLayer: isWebpackBundledLayer, |
|
|
resolve: { |
|
|
alias: createNextApiEsmAliases(), |
|
|
}, |
|
|
}, |
|
|
{ |
|
|
issuerLayer: shouldUseReactServerCondition, |
|
|
resolve: { |
|
|
alias: createAppRouterApiAliases(true), |
|
|
}, |
|
|
}, |
|
|
{ |
|
|
issuerLayer: isWebpackClientOnlyLayer, |
|
|
resolve: { |
|
|
alias: createAppRouterApiAliases(false), |
|
|
}, |
|
|
}, |
|
|
] |
|
|
: []), |
|
|
...(hasAppDir && !isClient |
|
|
? [ |
|
|
{ |
|
|
issuerLayer: shouldUseReactServerCondition, |
|
|
test: { |
|
|
|
|
|
|
|
|
and: [ |
|
|
aliasCodeConditionTest, |
|
|
{ |
|
|
not: [optOutBundlingPackageRegex, asyncStoragesRegex], |
|
|
}, |
|
|
], |
|
|
}, |
|
|
resourceQuery: { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
not: [ |
|
|
new RegExp(WEBPACK_RESOURCE_QUERIES.metadata), |
|
|
new RegExp(WEBPACK_RESOURCE_QUERIES.metadataImageMeta), |
|
|
], |
|
|
}, |
|
|
resolve: { |
|
|
mainFields: getMainField(compilerType, true), |
|
|
conditionNames: reactServerCondition, |
|
|
|
|
|
|
|
|
|
|
|
alias: createVendoredReactAliases(bundledReactChannel, { |
|
|
|
|
|
reactProductionProfiling, |
|
|
layer: WEBPACK_LAYERS.reactServerComponents, |
|
|
isBrowser: isClient, |
|
|
isEdgeServer, |
|
|
}), |
|
|
}, |
|
|
use: 'next-flight-loader', |
|
|
}, |
|
|
] |
|
|
: []), |
|
|
|
|
|
|
|
|
...(!config.experimental.fullySpecified |
|
|
? [ |
|
|
{ |
|
|
test: /\.m?js/, |
|
|
resolve: { |
|
|
fullySpecified: false, |
|
|
}, |
|
|
} as any, |
|
|
] |
|
|
: []), |
|
|
...(hasAppDir && isEdgeServer |
|
|
? [ |
|
|
|
|
|
|
|
|
|
|
|
{ |
|
|
resourceQuery: new RegExp( |
|
|
WEBPACK_RESOURCE_QUERIES.edgeSSREntry |
|
|
), |
|
|
layer: WEBPACK_LAYERS.reactServerComponents, |
|
|
}, |
|
|
] |
|
|
: []), |
|
|
...(hasAppDir |
|
|
? [ |
|
|
{ |
|
|
|
|
|
|
|
|
oneOf: [ |
|
|
{ |
|
|
issuerLayer: shouldUseReactServerCondition, |
|
|
test: { |
|
|
|
|
|
|
|
|
and: [ |
|
|
aliasCodeConditionTest, |
|
|
{ |
|
|
not: [optOutBundlingPackageRegex, asyncStoragesRegex], |
|
|
}, |
|
|
], |
|
|
}, |
|
|
resolve: { |
|
|
|
|
|
|
|
|
alias: createVendoredReactAliases(bundledReactChannel, { |
|
|
reactProductionProfiling, |
|
|
layer: WEBPACK_LAYERS.reactServerComponents, |
|
|
isBrowser: isClient, |
|
|
isEdgeServer, |
|
|
}), |
|
|
}, |
|
|
}, |
|
|
{ |
|
|
test: aliasCodeConditionTest, |
|
|
issuerLayer: WEBPACK_LAYERS.serverSideRendering, |
|
|
resolve: { |
|
|
alias: createVendoredReactAliases(bundledReactChannel, { |
|
|
reactProductionProfiling, |
|
|
layer: WEBPACK_LAYERS.serverSideRendering, |
|
|
isBrowser: isClient, |
|
|
isEdgeServer, |
|
|
}), |
|
|
}, |
|
|
}, |
|
|
], |
|
|
}, |
|
|
{ |
|
|
test: aliasCodeConditionTest, |
|
|
issuerLayer: WEBPACK_LAYERS.appPagesBrowser, |
|
|
resolve: { |
|
|
alias: createVendoredReactAliases(bundledReactChannel, { |
|
|
reactProductionProfiling, |
|
|
layer: WEBPACK_LAYERS.appPagesBrowser, |
|
|
isBrowser: isClient, |
|
|
isEdgeServer, |
|
|
}), |
|
|
}, |
|
|
}, |
|
|
] |
|
|
: []), |
|
|
|
|
|
...(hasAppDir && dev && isClient |
|
|
? [ |
|
|
{ |
|
|
test: codeCondition.test, |
|
|
exclude: [ |
|
|
|
|
|
codeCondition.exclude, |
|
|
transpilePackagesRegex, |
|
|
precompileRegex, |
|
|
], |
|
|
issuerLayer: WEBPACK_LAYERS.appPagesBrowser, |
|
|
use: reactRefreshLoaders, |
|
|
resolve: { |
|
|
mainFields: getMainField(compilerType, true), |
|
|
}, |
|
|
}, |
|
|
] |
|
|
: []), |
|
|
{ |
|
|
oneOf: [ |
|
|
{ |
|
|
...codeCondition, |
|
|
issuerLayer: WEBPACK_LAYERS.apiNode, |
|
|
use: apiRoutesLayerLoaders, |
|
|
|
|
|
|
|
|
parser: { |
|
|
url: true, |
|
|
}, |
|
|
}, |
|
|
{ |
|
|
...codeCondition, |
|
|
issuerLayer: WEBPACK_LAYERS.apiEdge, |
|
|
use: apiRoutesLayerLoaders, |
|
|
|
|
|
|
|
|
}, |
|
|
{ |
|
|
test: codeCondition.test, |
|
|
issuerLayer: WEBPACK_LAYERS.middleware, |
|
|
use: middlewareLayerLoaders, |
|
|
resolve: { |
|
|
mainFields: getMainField(compilerType, true), |
|
|
conditionNames: reactServerCondition, |
|
|
alias: createVendoredReactAliases(bundledReactChannel, { |
|
|
reactProductionProfiling, |
|
|
layer: WEBPACK_LAYERS.middleware, |
|
|
isBrowser: isClient, |
|
|
isEdgeServer, |
|
|
}), |
|
|
}, |
|
|
}, |
|
|
{ |
|
|
test: codeCondition.test, |
|
|
issuerLayer: WEBPACK_LAYERS.instrument, |
|
|
use: instrumentLayerLoaders, |
|
|
resolve: { |
|
|
mainFields: getMainField(compilerType, true), |
|
|
conditionNames: reactServerCondition, |
|
|
alias: createVendoredReactAliases(bundledReactChannel, { |
|
|
reactProductionProfiling, |
|
|
layer: WEBPACK_LAYERS.instrument, |
|
|
isBrowser: isClient, |
|
|
isEdgeServer, |
|
|
}), |
|
|
}, |
|
|
}, |
|
|
...(hasAppDir |
|
|
? [ |
|
|
{ |
|
|
test: codeCondition.test, |
|
|
issuerLayer: shouldUseReactServerCondition, |
|
|
exclude: asyncStoragesRegex, |
|
|
use: appServerLayerLoaders, |
|
|
}, |
|
|
{ |
|
|
test: codeCondition.test, |
|
|
resourceQuery: new RegExp( |
|
|
WEBPACK_RESOURCE_QUERIES.edgeSSREntry |
|
|
), |
|
|
use: appServerLayerLoaders, |
|
|
}, |
|
|
{ |
|
|
test: codeCondition.test, |
|
|
issuerLayer: WEBPACK_LAYERS.appPagesBrowser, |
|
|
|
|
|
exclude: browserNonTranspileModules, |
|
|
use: appBrowserLayerLoaders, |
|
|
resolve: { |
|
|
mainFields: getMainField(compilerType, true), |
|
|
}, |
|
|
}, |
|
|
{ |
|
|
test: codeCondition.test, |
|
|
issuerLayer: WEBPACK_LAYERS.serverSideRendering, |
|
|
exclude: asyncStoragesRegex, |
|
|
use: appSSRLayerLoaders, |
|
|
resolve: { |
|
|
mainFields: getMainField(compilerType, true), |
|
|
}, |
|
|
}, |
|
|
] |
|
|
: []), |
|
|
{ |
|
|
...codeCondition, |
|
|
use: [ |
|
|
...reactRefreshLoaders, |
|
|
defaultLoaders.babel, |
|
|
reactCompilerLoader, |
|
|
].filter(Boolean), |
|
|
}, |
|
|
], |
|
|
}, |
|
|
|
|
|
...(!config.images.disableStaticImages |
|
|
? [ |
|
|
{ |
|
|
test: nextImageLoaderRegex, |
|
|
loader: 'next-image-loader', |
|
|
issuer: { not: regexLikeCss }, |
|
|
dependency: { not: ['url'] }, |
|
|
resourceQuery: { |
|
|
not: [ |
|
|
new RegExp(WEBPACK_RESOURCE_QUERIES.metadata), |
|
|
new RegExp(WEBPACK_RESOURCE_QUERIES.metadataRoute), |
|
|
new RegExp(WEBPACK_RESOURCE_QUERIES.metadataImageMeta), |
|
|
], |
|
|
}, |
|
|
options: { |
|
|
isDev: dev, |
|
|
compilerType, |
|
|
basePath: config.basePath, |
|
|
assetPrefix: config.assetPrefix, |
|
|
}, |
|
|
}, |
|
|
] |
|
|
: []), |
|
|
...(isEdgeServer |
|
|
? [ |
|
|
{ |
|
|
resolve: { |
|
|
fallback: { |
|
|
process: require.resolve('./polyfills/process'), |
|
|
}, |
|
|
}, |
|
|
}, |
|
|
] |
|
|
: isClient |
|
|
? [ |
|
|
{ |
|
|
resolve: { |
|
|
fallback: |
|
|
config.experimental.fallbackNodePolyfills === false |
|
|
? { |
|
|
assert: false, |
|
|
buffer: false, |
|
|
constants: false, |
|
|
crypto: false, |
|
|
domain: false, |
|
|
http: false, |
|
|
https: false, |
|
|
os: false, |
|
|
path: false, |
|
|
punycode: false, |
|
|
process: false, |
|
|
querystring: false, |
|
|
stream: false, |
|
|
string_decoder: false, |
|
|
sys: false, |
|
|
timers: false, |
|
|
tty: false, |
|
|
util: false, |
|
|
vm: false, |
|
|
zlib: false, |
|
|
events: false, |
|
|
setImmediate: false, |
|
|
} |
|
|
: { |
|
|
assert: require.resolve( |
|
|
'next/dist/compiled/assert' |
|
|
), |
|
|
buffer: require.resolve( |
|
|
'next/dist/compiled/buffer' |
|
|
), |
|
|
constants: require.resolve( |
|
|
'next/dist/compiled/constants-browserify' |
|
|
), |
|
|
crypto: require.resolve( |
|
|
'next/dist/compiled/crypto-browserify' |
|
|
), |
|
|
domain: require.resolve( |
|
|
'next/dist/compiled/domain-browser' |
|
|
), |
|
|
http: require.resolve( |
|
|
'next/dist/compiled/stream-http' |
|
|
), |
|
|
https: require.resolve( |
|
|
'next/dist/compiled/https-browserify' |
|
|
), |
|
|
os: require.resolve( |
|
|
'next/dist/compiled/os-browserify' |
|
|
), |
|
|
path: require.resolve( |
|
|
'next/dist/compiled/path-browserify' |
|
|
), |
|
|
punycode: require.resolve( |
|
|
'next/dist/compiled/punycode' |
|
|
), |
|
|
process: require.resolve('./polyfills/process'), |
|
|
|
|
|
querystring: require.resolve( |
|
|
'next/dist/compiled/querystring-es3' |
|
|
), |
|
|
stream: require.resolve( |
|
|
'next/dist/compiled/stream-browserify' |
|
|
), |
|
|
string_decoder: require.resolve( |
|
|
'next/dist/compiled/string_decoder' |
|
|
), |
|
|
sys: require.resolve('next/dist/compiled/util'), |
|
|
timers: require.resolve( |
|
|
'next/dist/compiled/timers-browserify' |
|
|
), |
|
|
tty: require.resolve( |
|
|
'next/dist/compiled/tty-browserify' |
|
|
), |
|
|
|
|
|
|
|
|
util: require.resolve('next/dist/compiled/util'), |
|
|
vm: require.resolve( |
|
|
'next/dist/compiled/vm-browserify' |
|
|
), |
|
|
zlib: require.resolve( |
|
|
'next/dist/compiled/browserify-zlib' |
|
|
), |
|
|
events: require.resolve( |
|
|
'next/dist/compiled/events' |
|
|
), |
|
|
setImmediate: require.resolve( |
|
|
'next/dist/compiled/setimmediate' |
|
|
), |
|
|
}, |
|
|
}, |
|
|
}, |
|
|
] |
|
|
: []), |
|
|
{ |
|
|
|
|
|
|
|
|
test: /[\\/]next[\\/]dist[\\/](esm[\\/])?server[\\/]og[\\/]image-response\.js/, |
|
|
sideEffects: false, |
|
|
}, |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
{ |
|
|
test: /[\\/]next[\\/]dist[\\/](esm[\\/])?build[\\/]webpack[\\/]loaders[\\/]next-flight-loader[\\/]action-client-wrapper\.js/, |
|
|
sideEffects: false, |
|
|
}, |
|
|
{ |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
test: /__barrel_optimize__/, |
|
|
use: ({ resourceQuery }: { resourceQuery: string }) => { |
|
|
const names = ( |
|
|
resourceQuery.match(/\?names=([^&]+)/)?.[1] || '' |
|
|
).split(',') |
|
|
|
|
|
return [ |
|
|
{ |
|
|
loader: 'next-barrel-loader', |
|
|
options: { |
|
|
names, |
|
|
swcCacheDir: path.join( |
|
|
dir, |
|
|
config?.distDir ?? '.next', |
|
|
'cache', |
|
|
'swc' |
|
|
), |
|
|
}, |
|
|
|
|
|
|
|
|
|
|
|
ident: 'next-barrel-loader:' + resourceQuery, |
|
|
}, |
|
|
] |
|
|
}, |
|
|
}, |
|
|
{ |
|
|
resolve: { |
|
|
alias: { |
|
|
next: NEXT_PROJECT_ROOT, |
|
|
}, |
|
|
}, |
|
|
}, |
|
|
], |
|
|
}, |
|
|
plugins: [ |
|
|
isNodeServer && |
|
|
new bundler.NormalModuleReplacementPlugin( |
|
|
/\.\/(.+)\.shared-runtime$/, |
|
|
function (resource) { |
|
|
const moduleName = path.basename( |
|
|
resource.request, |
|
|
'.shared-runtime' |
|
|
) |
|
|
const layer = resource.contextInfo.issuerLayer |
|
|
let runtime |
|
|
|
|
|
switch (layer) { |
|
|
case WEBPACK_LAYERS.serverSideRendering: |
|
|
case WEBPACK_LAYERS.reactServerComponents: |
|
|
case WEBPACK_LAYERS.appPagesBrowser: |
|
|
case WEBPACK_LAYERS.actionBrowser: |
|
|
runtime = 'app-page' |
|
|
break |
|
|
case null: |
|
|
case undefined: |
|
|
default: |
|
|
runtime = 'pages' |
|
|
} |
|
|
resource.request = `next/dist/server/route-modules/${runtime}/vendored/contexts/${moduleName}` |
|
|
} |
|
|
), |
|
|
dev && new MemoryWithGcCachePlugin({ maxGenerations: 5 }), |
|
|
dev && |
|
|
isClient && |
|
|
(isRspack |
|
|
? |
|
|
new (getRspackReactRefresh() as any)({ |
|
|
injectLoader: false, |
|
|
injectEntry: false, |
|
|
overlay: false, |
|
|
}) |
|
|
: new ReactRefreshWebpackPlugin(webpack)), |
|
|
|
|
|
(isClient || isEdgeServer) && |
|
|
new bundler.ProvidePlugin({ |
|
|
|
|
|
Buffer: [require.resolve('buffer'), 'Buffer'], |
|
|
|
|
|
...(isClient && { process: [require.resolve('process')] }), |
|
|
}), |
|
|
|
|
|
new (getWebpackBundler().DefinePlugin)( |
|
|
getDefineEnv({ |
|
|
isTurbopack: false, |
|
|
config, |
|
|
dev, |
|
|
distDir, |
|
|
projectPath: dir, |
|
|
fetchCacheKeyPrefix, |
|
|
hasRewrites, |
|
|
isClient, |
|
|
isEdgeServer, |
|
|
isNodeServer, |
|
|
middlewareMatchers, |
|
|
omitNonDeterministic: isCompileMode, |
|
|
rewrites, |
|
|
}) |
|
|
), |
|
|
isClient && |
|
|
new ReactLoadablePlugin({ |
|
|
filename: REACT_LOADABLE_MANIFEST, |
|
|
pagesDir, |
|
|
appDir, |
|
|
runtimeAsset: `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`, |
|
|
dev, |
|
|
}), |
|
|
|
|
|
!isRspack && (isClient || isEdgeServer) && new DropClientPage(), |
|
|
isNodeServer && |
|
|
!dev && |
|
|
new (( |
|
|
require('./webpack/plugins/next-trace-entrypoints-plugin') as typeof import('./webpack/plugins/next-trace-entrypoints-plugin') |
|
|
) |
|
|
.TraceEntryPointsPlugin as typeof import('./webpack/plugins/next-trace-entrypoints-plugin').TraceEntryPointsPlugin)( |
|
|
{ |
|
|
rootDir: dir, |
|
|
appDir: appDir, |
|
|
pagesDir: pagesDir, |
|
|
esmExternals: config.experimental.esmExternals, |
|
|
outputFileTracingRoot: config.outputFileTracingRoot, |
|
|
appDirEnabled: hasAppDir, |
|
|
traceIgnores: [], |
|
|
compilerType, |
|
|
swcLoaderConfig: swcDefaultLoader, |
|
|
} |
|
|
), |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
config.excludeDefaultMomentLocales && |
|
|
new bundler.IgnorePlugin({ |
|
|
resourceRegExp: /^\.\/locale$/, |
|
|
contextRegExp: /moment$/, |
|
|
}), |
|
|
...(dev |
|
|
? (() => { |
|
|
|
|
|
|
|
|
const { NextJsRequireCacheHotReloader } = |
|
|
require('./webpack/plugins/nextjs-require-cache-hot-reloader') as typeof import('./webpack/plugins/nextjs-require-cache-hot-reloader') |
|
|
const devPlugins: any[] = [ |
|
|
new NextJsRequireCacheHotReloader({ |
|
|
serverComponents: hasAppDir, |
|
|
}), |
|
|
] |
|
|
|
|
|
if (isClient || isEdgeServer) { |
|
|
devPlugins.push(new bundler.HotModuleReplacementPlugin()) |
|
|
} |
|
|
|
|
|
return devPlugins |
|
|
})() |
|
|
: []), |
|
|
!dev && |
|
|
new bundler.IgnorePlugin({ |
|
|
resourceRegExp: /react-is/, |
|
|
contextRegExp: /next[\\/]dist[\\/]/, |
|
|
}), |
|
|
isNodeOrEdgeCompilation && |
|
|
new PagesManifestPlugin({ |
|
|
dev, |
|
|
appDirEnabled: hasAppDir, |
|
|
isEdgeRuntime: isEdgeServer, |
|
|
distDir: !dev ? distDir : undefined, |
|
|
}), |
|
|
|
|
|
|
|
|
isEdgeServer && |
|
|
new MiddlewarePlugin({ |
|
|
dev, |
|
|
sriEnabled: !dev && !!config.experimental.sri?.algorithm, |
|
|
rewrites, |
|
|
edgeEnvironments: { |
|
|
__NEXT_BUILD_ID: buildId, |
|
|
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: encryptionKey, |
|
|
__NEXT_PREVIEW_MODE_ID: previewProps.previewModeId, |
|
|
__NEXT_PREVIEW_MODE_SIGNING_KEY: previewProps.previewModeSigningKey, |
|
|
__NEXT_PREVIEW_MODE_ENCRYPTION_KEY: |
|
|
previewProps.previewModeEncryptionKey, |
|
|
}, |
|
|
}), |
|
|
isClient && |
|
|
new BuildManifestPlugin({ |
|
|
buildId, |
|
|
rewrites, |
|
|
isDevFallback, |
|
|
appDirEnabled: hasAppDir, |
|
|
clientRouterFilters, |
|
|
}), |
|
|
isRspack |
|
|
? new RspackProfilingPlugin({ runWebpackSpan }) |
|
|
: new ProfilingPlugin({ runWebpackSpan, rootDir: dir }), |
|
|
new WellKnownErrorsPlugin(), |
|
|
isClient && |
|
|
new CopyFilePlugin({ |
|
|
|
|
|
filePath: require.resolve('./polyfills/polyfill-nomodule'), |
|
|
cacheKey: process.env.__NEXT_VERSION as string, |
|
|
name: `static/chunks/polyfills${dev ? '' : '-[hash]'}.js`, |
|
|
minimize: false, |
|
|
info: { |
|
|
[CLIENT_STATIC_FILES_RUNTIME_POLYFILLS_SYMBOL]: 1, |
|
|
|
|
|
minimized: true, |
|
|
}, |
|
|
}), |
|
|
hasAppDir && isClient && new AppBuildManifestPlugin({ dev }), |
|
|
hasAppDir && |
|
|
(isClient |
|
|
? new ClientReferenceManifestPlugin({ |
|
|
dev, |
|
|
appDir, |
|
|
experimentalInlineCss: !!config.experimental.inlineCss, |
|
|
}) |
|
|
: new FlightClientEntryPlugin({ |
|
|
appDir, |
|
|
dev, |
|
|
isEdgeServer, |
|
|
encryptionKey, |
|
|
})), |
|
|
hasAppDir && |
|
|
!isClient && |
|
|
new NextTypesPlugin({ |
|
|
dir, |
|
|
distDir: config.distDir, |
|
|
appDir, |
|
|
dev, |
|
|
isEdgeServer, |
|
|
pageExtensions: config.pageExtensions, |
|
|
typedRoutes: enableTypedRoutes, |
|
|
cacheLifeConfig: config.experimental.cacheLife, |
|
|
originalRewrites, |
|
|
originalRedirects, |
|
|
}), |
|
|
!dev && |
|
|
isClient && |
|
|
!!config.experimental.sri?.algorithm && |
|
|
new SubresourceIntegrityPlugin(config.experimental.sri.algorithm), |
|
|
isClient && |
|
|
new NextFontManifestPlugin({ |
|
|
appDir, |
|
|
}), |
|
|
!dev && |
|
|
isClient && |
|
|
config.experimental.cssChunking && |
|
|
(isRspack |
|
|
? new (getRspackCore().experiments.CssChunkingPlugin)({ |
|
|
strict: config.experimental.cssChunking === 'strict', |
|
|
nextjs: true, |
|
|
}) |
|
|
: new CssChunkingPlugin( |
|
|
config.experimental.cssChunking === 'strict' |
|
|
)), |
|
|
telemetryPlugin, |
|
|
!dev && |
|
|
isNodeServer && |
|
|
new ( |
|
|
require('./webpack/plugins/telemetry-plugin/telemetry-plugin') as typeof import('./webpack/plugins/telemetry-plugin/telemetry-plugin') |
|
|
).TelemetryPlugin(new Map()), |
|
|
shouldEnableSlowModuleDetection && |
|
|
new ( |
|
|
require('./webpack/plugins/slow-module-detection-plugin') as typeof import('./webpack/plugins/slow-module-detection-plugin') |
|
|
).default({ |
|
|
compilerType, |
|
|
...config.experimental.slowModuleDetection!, |
|
|
}), |
|
|
].filter(Boolean as any as ExcludesFalse), |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
if (resolvedBaseUrl && !resolvedBaseUrl.isImplicit) { |
|
|
webpackConfig.resolve?.modules?.push(resolvedBaseUrl.baseUrl) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
webpackConfig.resolve?.plugins?.unshift( |
|
|
new JsConfigPathsPlugin( |
|
|
jsConfig?.compilerOptions?.paths || {}, |
|
|
resolvedBaseUrl |
|
|
) |
|
|
) |
|
|
|
|
|
const webpack5Config = webpackConfig as webpack.Configuration |
|
|
|
|
|
if (isEdgeServer) { |
|
|
webpack5Config.module?.rules?.unshift({ |
|
|
test: /\.wasm$/, |
|
|
loader: 'next-middleware-wasm-loader', |
|
|
type: 'javascript/auto', |
|
|
resourceQuery: /module/i, |
|
|
}) |
|
|
webpack5Config.module?.rules?.unshift({ |
|
|
dependency: 'url', |
|
|
loader: 'next-middleware-asset-loader', |
|
|
type: 'javascript/auto', |
|
|
layer: WEBPACK_LAYERS.edgeAsset, |
|
|
}) |
|
|
webpack5Config.module?.rules?.unshift({ |
|
|
issuerLayer: WEBPACK_LAYERS.edgeAsset, |
|
|
type: 'asset/source', |
|
|
}) |
|
|
} |
|
|
|
|
|
webpack5Config.experiments = { |
|
|
layers: true, |
|
|
cacheUnaffected: true, |
|
|
buildHttp: Array.isArray(config.experimental.urlImports) |
|
|
? { |
|
|
allowedUris: config.experimental.urlImports, |
|
|
cacheLocation: path.join(dir, 'next.lock/data'), |
|
|
lockfileLocation: path.join(dir, 'next.lock/lock.json'), |
|
|
} |
|
|
: config.experimental.urlImports |
|
|
? { |
|
|
cacheLocation: path.join(dir, 'next.lock/data'), |
|
|
lockfileLocation: path.join(dir, 'next.lock/lock.json'), |
|
|
...config.experimental.urlImports, |
|
|
} |
|
|
: undefined, |
|
|
} |
|
|
|
|
|
webpack5Config.module!.parser = { |
|
|
javascript: { |
|
|
url: 'relative', |
|
|
}, |
|
|
} |
|
|
webpack5Config.module!.generator = { |
|
|
asset: { |
|
|
filename: 'static/media/[name].[hash:8][ext]', |
|
|
}, |
|
|
} |
|
|
|
|
|
if (!webpack5Config.output) { |
|
|
webpack5Config.output = {} |
|
|
} |
|
|
if (isClient) { |
|
|
webpack5Config.output.trustedTypes = 'nextjs#bundler' |
|
|
} |
|
|
|
|
|
if (isClient || isEdgeServer) { |
|
|
webpack5Config.output.enabledLibraryTypes = ['assign'] |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
webpack5Config.snapshot = {} |
|
|
if (process.versions.pnp === '3') { |
|
|
webpack5Config.snapshot.managedPaths = [ |
|
|
/^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/, |
|
|
] |
|
|
} else { |
|
|
webpack5Config.snapshot.managedPaths = [/^(.+?[\\/]node_modules[\\/])/] |
|
|
} |
|
|
if (process.versions.pnp === '3') { |
|
|
webpack5Config.snapshot.immutablePaths = [ |
|
|
/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/, |
|
|
] |
|
|
} |
|
|
|
|
|
if (dev) { |
|
|
if (!webpack5Config.optimization) { |
|
|
webpack5Config.optimization = {} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
if (!hasAppDir) { |
|
|
webpack5Config.optimization.providedExports = false |
|
|
} |
|
|
webpack5Config.optimization.usedExports = false |
|
|
} |
|
|
|
|
|
const configVars = JSON.stringify({ |
|
|
optimizePackageImports: config?.experimental?.optimizePackageImports, |
|
|
crossOrigin: config.crossOrigin, |
|
|
pageExtensions: pageExtensions, |
|
|
trailingSlash: config.trailingSlash, |
|
|
buildActivityPosition: |
|
|
config.devIndicators === false |
|
|
? undefined |
|
|
: config.devIndicators.position, |
|
|
productionBrowserSourceMaps: !!config.productionBrowserSourceMaps, |
|
|
reactStrictMode: config.reactStrictMode, |
|
|
optimizeCss: config.experimental.optimizeCss, |
|
|
nextScriptWorkers: config.experimental.nextScriptWorkers, |
|
|
scrollRestoration: config.experimental.scrollRestoration, |
|
|
typedRoutes: config.experimental.typedRoutes, |
|
|
basePath: config.basePath, |
|
|
excludeDefaultMomentLocales: config.excludeDefaultMomentLocales, |
|
|
assetPrefix: config.assetPrefix, |
|
|
disableOptimizedLoading, |
|
|
isEdgeRuntime: isEdgeServer, |
|
|
reactProductionProfiling, |
|
|
webpack: !!config.webpack, |
|
|
hasRewrites, |
|
|
swcLoader: useSWCLoader, |
|
|
removeConsole: config.compiler?.removeConsole, |
|
|
reactRemoveProperties: config.compiler?.reactRemoveProperties, |
|
|
styledComponents: config.compiler?.styledComponents, |
|
|
relay: config.compiler?.relay, |
|
|
emotion: config.compiler?.emotion, |
|
|
modularizeImports: config.modularizeImports, |
|
|
imageLoaderFile: config.images.loaderFile, |
|
|
clientTraceMetadata: config.experimental.clientTraceMetadata, |
|
|
serverSourceMaps: config.experimental.serverSourceMaps, |
|
|
serverReferenceHashSalt: encryptionKey, |
|
|
}) |
|
|
|
|
|
const cache: any = { |
|
|
type: 'filesystem', |
|
|
|
|
|
maxMemoryGenerations: dev ? 0 : Infinity, |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
version: `${__dirname}|${process.env.__NEXT_VERSION}|${configVars}`, |
|
|
cacheDirectory: path.join(distDir, 'cache', 'webpack'), |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
compression: dev ? 'gzip' : false, |
|
|
} |
|
|
|
|
|
|
|
|
if (config.webpack && config.configFile) { |
|
|
cache.buildDependencies = { |
|
|
config: [config.configFile], |
|
|
|
|
|
defaultWebpack: [], |
|
|
} |
|
|
} else { |
|
|
cache.buildDependencies = { |
|
|
|
|
|
defaultWebpack: [], |
|
|
} |
|
|
} |
|
|
webpack5Config.plugins?.push((compiler) => { |
|
|
compiler.hooks.done.tap('next-build-dependencies', (stats) => { |
|
|
const buildDependencies = stats.compilation.buildDependencies |
|
|
const nextPackage = path.dirname(require.resolve('next/package.json')) |
|
|
|
|
|
|
|
|
for (const dep of buildDependencies) { |
|
|
if (dep.startsWith(nextPackage)) { |
|
|
buildDependencies.delete(dep) |
|
|
} |
|
|
} |
|
|
}) |
|
|
}) |
|
|
|
|
|
webpack5Config.cache = cache |
|
|
|
|
|
if (process.env.NEXT_WEBPACK_LOGGING) { |
|
|
const infra = process.env.NEXT_WEBPACK_LOGGING.includes('infrastructure') |
|
|
const profileClient = |
|
|
process.env.NEXT_WEBPACK_LOGGING.includes('profile-client') |
|
|
const profileServer = |
|
|
process.env.NEXT_WEBPACK_LOGGING.includes('profile-server') |
|
|
const summaryClient = |
|
|
process.env.NEXT_WEBPACK_LOGGING.includes('summary-client') |
|
|
const summaryServer = |
|
|
process.env.NEXT_WEBPACK_LOGGING.includes('summary-server') |
|
|
|
|
|
const profile = |
|
|
(profileClient && isClient) || (profileServer && isNodeOrEdgeCompilation) |
|
|
const summary = |
|
|
(summaryClient && isClient) || (summaryServer && isNodeOrEdgeCompilation) |
|
|
|
|
|
const logDefault = !infra && !profile && !summary |
|
|
|
|
|
if (logDefault || infra) { |
|
|
webpack5Config.infrastructureLogging = { |
|
|
level: 'verbose', |
|
|
debug: /FileSystemInfo/, |
|
|
} |
|
|
} |
|
|
|
|
|
if (logDefault || profile) { |
|
|
webpack5Config.plugins!.push((compiler: webpack.Compiler) => { |
|
|
compiler.hooks.done.tap('next-webpack-logging', (stats) => { |
|
|
console.log( |
|
|
stats.toString({ |
|
|
colors: true, |
|
|
logging: logDefault ? 'log' : 'verbose', |
|
|
}) |
|
|
) |
|
|
}) |
|
|
}) |
|
|
} else if (summary) { |
|
|
webpack5Config.plugins!.push((compiler: webpack.Compiler) => { |
|
|
compiler.hooks.done.tap('next-webpack-logging', (stats) => { |
|
|
console.log( |
|
|
stats.toString({ |
|
|
preset: 'summary', |
|
|
colors: true, |
|
|
timings: true, |
|
|
}) |
|
|
) |
|
|
}) |
|
|
}) |
|
|
} |
|
|
|
|
|
if (profile) { |
|
|
const ProgressPlugin = |
|
|
webpack.ProgressPlugin as unknown as typeof webpack.ProgressPlugin |
|
|
webpack5Config.plugins!.push( |
|
|
new ProgressPlugin({ |
|
|
profile: true, |
|
|
}) |
|
|
) |
|
|
webpack5Config.profile = true |
|
|
} |
|
|
} |
|
|
|
|
|
webpackConfig = await buildConfiguration(webpackConfig, { |
|
|
supportedBrowsers, |
|
|
rootDirectory: dir, |
|
|
customAppFile: pagesDir |
|
|
? new RegExp(escapeStringRegexp(path.join(pagesDir, `_app`))) |
|
|
: undefined, |
|
|
hasAppDir, |
|
|
isDevelopment: dev, |
|
|
isServer: isNodeOrEdgeCompilation, |
|
|
isEdgeRuntime: isEdgeServer, |
|
|
targetWeb: isClient || isEdgeServer, |
|
|
assetPrefix: config.assetPrefix || '', |
|
|
sassOptions: config.sassOptions, |
|
|
productionBrowserSourceMaps: config.productionBrowserSourceMaps, |
|
|
future: config.future, |
|
|
experimental: config.experimental, |
|
|
disableStaticImages: config.images.disableStaticImages, |
|
|
transpilePackages: config.transpilePackages, |
|
|
serverSourceMaps: config.experimental.serverSourceMaps, |
|
|
}) |
|
|
|
|
|
|
|
|
webpackConfig.cache.name = `${webpackConfig.name}-${webpackConfig.mode}${ |
|
|
isDevFallback ? '-fallback' : '' |
|
|
}` |
|
|
|
|
|
if (dev) { |
|
|
if (webpackConfig.module) { |
|
|
webpackConfig.module.unsafeCache = (module: any) => |
|
|
!UNSAFE_CACHE_REGEX.test(module.resource) |
|
|
} else { |
|
|
webpackConfig.module = { |
|
|
unsafeCache: (module: any) => !UNSAFE_CACHE_REGEX.test(module.resource), |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
let originalDevtool = webpackConfig.devtool |
|
|
if (typeof config.webpack === 'function') { |
|
|
const pluginCountBefore = webpackConfig.plugins?.length |
|
|
|
|
|
webpackConfig = config.webpack(webpackConfig, { |
|
|
dir, |
|
|
dev, |
|
|
isServer: isNodeOrEdgeCompilation, |
|
|
buildId, |
|
|
config, |
|
|
defaultLoaders, |
|
|
totalPages: Object.keys(entrypoints).length, |
|
|
webpack: bundler, |
|
|
...(isNodeOrEdgeCompilation |
|
|
? { |
|
|
nextRuntime: isEdgeServer ? 'edge' : 'nodejs', |
|
|
} |
|
|
: {}), |
|
|
}) |
|
|
|
|
|
if (telemetryPlugin && pluginCountBefore) { |
|
|
const pluginCountAfter = webpackConfig.plugins?.length |
|
|
if (pluginCountAfter) { |
|
|
const pluginsChanged = pluginCountAfter !== pluginCountBefore |
|
|
telemetryPlugin.addUsage('webpackPlugins', pluginsChanged ? 1 : 0) |
|
|
} |
|
|
} |
|
|
|
|
|
if (!webpackConfig) { |
|
|
throw new Error( |
|
|
`Webpack config is undefined. You may have forgot to return properly from within the "webpack" method of your ${config.configFileName}.\n` + |
|
|
'See more info here https://nextjs.org/docs/messages/undefined-webpack-config' |
|
|
) |
|
|
} |
|
|
|
|
|
if (dev && originalDevtool !== webpackConfig.devtool) { |
|
|
webpackConfig.devtool = originalDevtool |
|
|
devtoolRevertWarning(originalDevtool) |
|
|
} |
|
|
|
|
|
|
|
|
const webpack5Config = webpackConfig as webpack.Configuration |
|
|
|
|
|
|
|
|
if (webpack5Config.experiments?.lazyCompilation === true) { |
|
|
webpack5Config.experiments.lazyCompilation = { |
|
|
entries: false, |
|
|
} |
|
|
} else if ( |
|
|
typeof webpack5Config.experiments?.lazyCompilation === 'object' && |
|
|
webpack5Config.experiments.lazyCompilation.entries !== false |
|
|
) { |
|
|
webpack5Config.experiments.lazyCompilation.entries = false |
|
|
} |
|
|
|
|
|
if (typeof (webpackConfig as any).then === 'function') { |
|
|
console.warn( |
|
|
'> Promise returned in next config. https://nextjs.org/docs/messages/promise-in-next-config' |
|
|
) |
|
|
} |
|
|
} |
|
|
const rules = webpackConfig.module?.rules || [] |
|
|
|
|
|
const customSvgRule = rules.find( |
|
|
(rule): rule is webpack.RuleSetRule => |
|
|
(rule && |
|
|
typeof rule === 'object' && |
|
|
rule.loader !== 'next-image-loader' && |
|
|
'test' in rule && |
|
|
rule.test instanceof RegExp && |
|
|
rule.test.test('.svg')) || |
|
|
false |
|
|
) |
|
|
|
|
|
if (customSvgRule && hasAppDir) { |
|
|
|
|
|
|
|
|
|
|
|
rules.push({ |
|
|
test: customSvgRule.test, |
|
|
oneOf: [ |
|
|
WEBPACK_LAYERS.reactServerComponents, |
|
|
WEBPACK_LAYERS.serverSideRendering, |
|
|
WEBPACK_LAYERS.appPagesBrowser, |
|
|
].map((layer) => ({ |
|
|
issuerLayer: layer, |
|
|
resolve: { |
|
|
alias: createVendoredReactAliases(bundledReactChannel, { |
|
|
reactProductionProfiling, |
|
|
layer, |
|
|
isBrowser: isClient, |
|
|
isEdgeServer, |
|
|
}), |
|
|
}, |
|
|
})), |
|
|
}) |
|
|
} |
|
|
|
|
|
if (!config.images.disableStaticImages) { |
|
|
const nextImageRule = rules.find( |
|
|
(rule) => |
|
|
rule && typeof rule === 'object' && rule.loader === 'next-image-loader' |
|
|
) |
|
|
if (customSvgRule && nextImageRule && typeof nextImageRule === 'object') { |
|
|
|
|
|
|
|
|
|
|
|
nextImageRule.test = /\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$/i |
|
|
} |
|
|
} |
|
|
|
|
|
if ( |
|
|
config.experimental.craCompat && |
|
|
webpackConfig.module?.rules && |
|
|
webpackConfig.plugins |
|
|
) { |
|
|
|
|
|
|
|
|
|
|
|
const fileLoaderExclude = [/\.(js|mjs|jsx|ts|tsx|json)$/] |
|
|
const fileLoader = { |
|
|
exclude: fileLoaderExclude, |
|
|
issuer: fileLoaderExclude, |
|
|
type: 'asset/resource', |
|
|
} |
|
|
|
|
|
const topRules = [] |
|
|
const innerRules = [] |
|
|
|
|
|
for (const rule of webpackConfig.module.rules) { |
|
|
if (!rule || typeof rule !== 'object') continue |
|
|
if (rule.resolve) { |
|
|
topRules.push(rule) |
|
|
} else { |
|
|
if ( |
|
|
rule.oneOf && |
|
|
!(rule.test || rule.exclude || rule.resource || rule.issuer) |
|
|
) { |
|
|
rule.oneOf.forEach((r) => innerRules.push(r)) |
|
|
} else { |
|
|
innerRules.push(rule) |
|
|
} |
|
|
} |
|
|
} |
|
|
|
|
|
webpackConfig.module.rules = [ |
|
|
...(topRules as any), |
|
|
{ |
|
|
oneOf: [...innerRules, fileLoader], |
|
|
}, |
|
|
] |
|
|
} |
|
|
|
|
|
|
|
|
if (typeof config.webpackDevMiddleware === 'function') { |
|
|
const options = config.webpackDevMiddleware({ |
|
|
watchOptions: webpackConfig.watchOptions, |
|
|
}) |
|
|
if (options.watchOptions) { |
|
|
webpackConfig.watchOptions = options.watchOptions |
|
|
} |
|
|
} |
|
|
|
|
|
function canMatchCss(rule: webpack.RuleSetCondition | undefined): boolean { |
|
|
if (!rule) { |
|
|
return false |
|
|
} |
|
|
|
|
|
const fileNames = [ |
|
|
'/tmp/NEXTJS_CSS_DETECTION_FILE.css', |
|
|
'/tmp/NEXTJS_CSS_DETECTION_FILE.scss', |
|
|
'/tmp/NEXTJS_CSS_DETECTION_FILE.sass', |
|
|
'/tmp/NEXTJS_CSS_DETECTION_FILE.less', |
|
|
'/tmp/NEXTJS_CSS_DETECTION_FILE.styl', |
|
|
] |
|
|
|
|
|
if (rule instanceof RegExp && fileNames.some((input) => rule.test(input))) { |
|
|
return true |
|
|
} |
|
|
|
|
|
if (typeof rule === 'function') { |
|
|
if ( |
|
|
fileNames.some((input) => { |
|
|
try { |
|
|
if (rule(input)) { |
|
|
return true |
|
|
} |
|
|
} catch {} |
|
|
return false |
|
|
}) |
|
|
) { |
|
|
return true |
|
|
} |
|
|
} |
|
|
|
|
|
if (Array.isArray(rule) && rule.some(canMatchCss)) { |
|
|
return true |
|
|
} |
|
|
|
|
|
return false |
|
|
} |
|
|
|
|
|
const hasUserCssConfig = |
|
|
webpackConfig.module?.rules?.some( |
|
|
(rule: any) => canMatchCss(rule.test) || canMatchCss(rule.include) |
|
|
) ?? false |
|
|
|
|
|
if (hasUserCssConfig) { |
|
|
|
|
|
if (isNodeOrEdgeCompilation) { |
|
|
console.warn( |
|
|
yellow(bold('Warning: ')) + |
|
|
bold( |
|
|
'Built-in CSS support is being disabled due to custom CSS configuration being detected.\n' |
|
|
) + |
|
|
'See here for more info: https://nextjs.org/docs/messages/built-in-css-disabled\n' |
|
|
) |
|
|
} |
|
|
|
|
|
if (webpackConfig.module?.rules?.length) { |
|
|
|
|
|
webpackConfig.module.rules.forEach((r) => { |
|
|
if (!r || typeof r !== 'object') return |
|
|
if (Array.isArray(r.oneOf)) { |
|
|
r.oneOf = r.oneOf.filter( |
|
|
(o) => (o as any)[Symbol.for('__next_css_remove')] !== true |
|
|
) |
|
|
} |
|
|
}) |
|
|
} |
|
|
if (webpackConfig.plugins?.length) { |
|
|
|
|
|
webpackConfig.plugins = webpackConfig.plugins.filter( |
|
|
(p) => (p as any).__next_css_remove !== true |
|
|
) |
|
|
} |
|
|
if (webpackConfig.optimization?.minimizer?.length) { |
|
|
|
|
|
webpackConfig.optimization.minimizer = |
|
|
webpackConfig.optimization.minimizer.filter( |
|
|
(e) => (e as any).__next_css_remove !== true |
|
|
) |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
if (dev && isClient) { |
|
|
attachReactRefresh(webpackConfig, defaultLoaders.babel) |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const originalEntry: any = webpackConfig.entry |
|
|
if (typeof originalEntry !== 'undefined') { |
|
|
const updatedEntry = async () => { |
|
|
const entry: webpack.EntryObject = |
|
|
typeof originalEntry === 'function' |
|
|
? await originalEntry() |
|
|
: originalEntry |
|
|
|
|
|
if ( |
|
|
clientEntries && |
|
|
Array.isArray(entry['main.js']) && |
|
|
entry['main.js'].length > 0 |
|
|
) { |
|
|
const originalFile = clientEntries[ |
|
|
CLIENT_STATIC_FILES_RUNTIME_MAIN |
|
|
] as string |
|
|
entry[CLIENT_STATIC_FILES_RUNTIME_MAIN] = [ |
|
|
...entry['main.js'], |
|
|
originalFile, |
|
|
] |
|
|
} |
|
|
delete entry['main.js'] |
|
|
|
|
|
for (const name of Object.keys(entry)) { |
|
|
entry[name] = finalizeEntrypoint({ |
|
|
value: entry[name], |
|
|
compilerType, |
|
|
name, |
|
|
hasAppDir, |
|
|
}) |
|
|
} |
|
|
|
|
|
return entry |
|
|
} |
|
|
|
|
|
webpackConfig.entry = updatedEntry |
|
|
} |
|
|
|
|
|
if (!dev && typeof webpackConfig.entry === 'function') { |
|
|
|
|
|
webpackConfig.entry = await webpackConfig.entry() |
|
|
} |
|
|
|
|
|
return webpackConfig |
|
|
} |
|
|
|