Unverified Commit 3c2a1959 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Also enforce experimental features when there's no next config file (#81679)

When running `next build --debug-prerender`, we also want to set the experimental features even if there is no next.config.js file present.

This PR also fixes the `cloneObject` function to better handle nested optional object properties, and we're now also freezing and cloning the default config before applying changes to it.

> [!NOTE]  
> This PR is best reviewed with hidden whitespace changes.
parent 1a0c4d08
...@@ -1283,7 +1283,7 @@ export interface NextConfig extends Record<string, any> { ...@@ -1283,7 +1283,7 @@ export interface NextConfig extends Record<string, any> {
htmlLimitedBots?: RegExp htmlLimitedBots?: RegExp
} }
export const defaultConfig = { export const defaultConfig = Object.freeze({
env: {}, env: {},
webpack: null, webpack: null,
eslint: { eslint: {
...@@ -1503,7 +1503,7 @@ export const defaultConfig = { ...@@ -1503,7 +1503,7 @@ export const defaultConfig = {
}, },
htmlLimitedBots: undefined, htmlLimitedBots: undefined,
bundlePagesRouterDependencies: false, bundlePagesRouterDependencies: false,
} satisfies NextConfig } satisfies NextConfig)
export async function normalizeConfig(phase: string, config: any) { export async function normalizeConfig(phase: string, config: any) {
if (typeof config === 'function') { if (typeof config === 'function') {
......
...@@ -1227,6 +1227,7 @@ export default async function loadConfig( ...@@ -1227,6 +1227,7 @@ export default async function loadConfig(
} }
const path = await findUp(CONFIG_FILES, { cwd: dir }) const path = await findUp(CONFIG_FILES, { cwd: dir })
const configuredExperimentalFeatures: ConfiguredExperimentalFeature[] = []
// If config file was found // If config file was found
if (path?.length) { if (path?.length) {
...@@ -1280,8 +1281,6 @@ export default async function loadConfig( ...@@ -1280,8 +1281,6 @@ export default async function loadConfig(
)) as NextConfig )) as NextConfig
) )
const configuredExperimentalFeatures: ConfiguredExperimentalFeature[] = []
if (reportExperimentalFeatures && loadedConfig.experimental) { if (reportExperimentalFeatures && loadedConfig.experimental) {
for (const name of Object.keys( for (const name of Object.keys(
loadedConfig.experimental loadedConfig.experimental
...@@ -1420,58 +1419,13 @@ export default async function loadConfig( ...@@ -1420,58 +1419,13 @@ export default async function loadConfig(
userConfig.htmlLimitedBots = userConfig.htmlLimitedBots.source userConfig.htmlLimitedBots = userConfig.htmlLimitedBots.source
} }
if ( enforceExperimentalFeatures(userConfig, {
userConfig.experimental && configuredExperimentalFeatures: reportExperimentalFeatures
userConfig.experimental.enablePrerenderSourceMaps === undefined && ? configuredExperimentalFeatures
userConfig.experimental.dynamicIO === true : undefined,
) { debugPrerender,
userConfig.experimental.enablePrerenderSourceMaps = true phase,
addConfiguredExperimentalFeature( })
configuredExperimentalFeatures,
'enablePrerenderSourceMaps',
true,
'enabled by `experimental.dynamicIO`'
)
}
if (
debugPrerender &&
(phase === PHASE_PRODUCTION_BUILD || phase === PHASE_EXPORT)
) {
userConfig.experimental ??= {}
setExperimentalFeatureForDebugPrerender(
userConfig.experimental,
'serverSourceMaps',
true,
reportExperimentalFeatures ? configuredExperimentalFeatures : undefined
)
setExperimentalFeatureForDebugPrerender(
userConfig.experimental,
process.env.TURBOPACK ? 'turbopackMinify' : 'serverMinification',
false,
reportExperimentalFeatures ? configuredExperimentalFeatures : undefined
)
setExperimentalFeatureForDebugPrerender(
userConfig.experimental,
'enablePrerenderSourceMaps',
true,
reportExperimentalFeatures ? configuredExperimentalFeatures : undefined
)
setExperimentalFeatureForDebugPrerender(
userConfig.experimental,
'prerenderEarlyExit',
false,
reportExperimentalFeatures ? configuredExperimentalFeatures : undefined
)
}
if (reportExperimentalFeatures) {
reportExperimentalFeatures(configuredExperimentalFeatures)
}
const completeConfig = assignDefaults( const completeConfig = assignDefaults(
dir, dir,
...@@ -1483,6 +1437,11 @@ export default async function loadConfig( ...@@ -1483,6 +1437,11 @@ export default async function loadConfig(
}, },
silent silent
) as NextConfigComplete ) as NextConfigComplete
if (reportExperimentalFeatures) {
reportExperimentalFeatures(configuredExperimentalFeatures)
}
return await applyModifyConfig(completeConfig, phase, silent) return await applyModifyConfig(completeConfig, phase, silent)
} else { } else {
const configBaseName = basename(CONFIG_FILES[0], extname(CONFIG_FILES[0])) const configBaseName = basename(CONFIG_FILES[0], extname(CONFIG_FILES[0]))
...@@ -1506,14 +1465,30 @@ export default async function loadConfig( ...@@ -1506,14 +1465,30 @@ export default async function loadConfig(
} }
} }
const clonedDefaultConfig = cloneObject(defaultConfig) as NextConfig
enforceExperimentalFeatures(clonedDefaultConfig, {
configuredExperimentalFeatures: reportExperimentalFeatures
? configuredExperimentalFeatures
: undefined,
debugPrerender,
phase,
})
// always call assignDefaults to ensure settings like // always call assignDefaults to ensure settings like
// reactRoot can be updated correctly even with no next.config.js // reactRoot can be updated correctly even with no next.config.js
const completeConfig = assignDefaults( const completeConfig = assignDefaults(
dir, dir,
{ ...defaultConfig, configFileName }, { ...clonedDefaultConfig, configFileName },
silent silent
) as NextConfigComplete ) as NextConfigComplete
setHttpClientAndAgentOptions(completeConfig) setHttpClientAndAgentOptions(completeConfig)
if (reportExperimentalFeatures) {
reportExperimentalFeatures(configuredExperimentalFeatures)
}
return await applyModifyConfig(completeConfig, phase, silent) return await applyModifyConfig(completeConfig, phase, silent)
} }
...@@ -1523,7 +1498,70 @@ export type ConfiguredExperimentalFeature = { ...@@ -1523,7 +1498,70 @@ export type ConfiguredExperimentalFeature = {
reason?: string reason?: string
} }
export function addConfiguredExperimentalFeature< function enforceExperimentalFeatures(
config: NextConfig,
options: {
configuredExperimentalFeatures: ConfiguredExperimentalFeature[] | undefined
debugPrerender: boolean | undefined
phase: string
}
) {
const { configuredExperimentalFeatures, debugPrerender, phase } = options
if (
config.experimental &&
config.experimental.enablePrerenderSourceMaps === undefined &&
config.experimental.dynamicIO === true
) {
config.experimental.enablePrerenderSourceMaps = true
if (configuredExperimentalFeatures) {
addConfiguredExperimentalFeature(
configuredExperimentalFeatures,
'enablePrerenderSourceMaps',
true,
'enabled by `experimental.dynamicIO`'
)
}
}
config.experimental ??= {}
if (
debugPrerender &&
(phase === PHASE_PRODUCTION_BUILD || phase === PHASE_EXPORT)
) {
setExperimentalFeatureForDebugPrerender(
config.experimental,
'serverSourceMaps',
true,
configuredExperimentalFeatures
)
setExperimentalFeatureForDebugPrerender(
config.experimental,
process.env.TURBOPACK ? 'turbopackMinify' : 'serverMinification',
false,
configuredExperimentalFeatures
)
setExperimentalFeatureForDebugPrerender(
config.experimental,
'enablePrerenderSourceMaps',
true,
configuredExperimentalFeatures
)
setExperimentalFeatureForDebugPrerender(
config.experimental,
'prerenderEarlyExit',
false,
configuredExperimentalFeatures
)
}
}
function addConfiguredExperimentalFeature<
KeyType extends keyof ExperimentalConfig, KeyType extends keyof ExperimentalConfig,
>( >(
configuredExperimentalFeatures: ConfiguredExperimentalFeature[], configuredExperimentalFeatures: ConfiguredExperimentalFeature[],
...@@ -1564,20 +1602,50 @@ function setExperimentalFeatureForDebugPrerender< ...@@ -1564,20 +1602,50 @@ function setExperimentalFeatureForDebugPrerender<
} }
function cloneObject(obj: any): any { function cloneObject(obj: any): any {
// Primitives & null
if (obj === null || typeof obj !== 'object') { if (obj === null || typeof obj !== 'object') {
return obj return obj
} }
// RegExp → clone via constructor
if (obj instanceof RegExp) {
return new RegExp(obj.source, obj.flags)
}
// Function → just reuse the function reference
if (typeof obj === 'function') {
return obj
}
// Arrays → map each element
if (Array.isArray(obj)) { if (Array.isArray(obj)) {
return obj.map(cloneObject) return obj.map(cloneObject)
} }
const keys = Object.keys(obj)
if (keys.length === 0) { // Detect non‑plain objects (class instances)
const proto = Object.getPrototypeOf(obj)
const isPlainObject = proto === Object.prototype || proto === null
// If it's not a plain object, just return the original
if (!isPlainObject) {
return obj return obj
} }
return keys.reduce((acc, key) => { // Plain object → create a new object with the same prototype
;(acc as any)[key] = cloneObject(obj[key]) // and copy all properties, cloning data properties and keeping
return acc // accessor properties (getters/setters) as‑is.
}, {}) const result = Object.create(proto)
for (const key of Reflect.ownKeys(obj)) {
const descriptor = Object.getOwnPropertyDescriptor(obj, key)
if (descriptor && (descriptor.get || descriptor.set)) {
// Accessor property → copy descriptor as‑is (get/set functions)
Object.defineProperty(result, key, descriptor)
} else {
// Data property → clone the value
result[key] = cloneObject(obj[key])
}
}
return result
} }
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import path from 'path'
const { version: nextVersion } = require('next/package.json') const { version: nextVersion } = require('next/package.json')
describe('build-output-prerender', () => { describe('build-output-prerender', () => {
describe('with a next config file', () => {
describe('without --debug-prerender', () => { describe('without --debug-prerender', () => {
const { next, isTurbopack } = nextTestSetup({ const { next, isTurbopack } = nextTestSetup({
files: __dirname, files: path.join(__dirname, 'fixtures/with-config-file'),
skipStart: true, skipStart: true,
}) })
...@@ -60,7 +62,7 @@ describe('build-output-prerender', () => { ...@@ -60,7 +62,7 @@ describe('build-output-prerender', () => {
describe('with --debug-prerender', () => { describe('with --debug-prerender', () => {
const { next, isTurbopack } = nextTestSetup({ const { next, isTurbopack } = nextTestSetup({
files: __dirname, files: path.join(__dirname, 'fixtures/with-config-file'),
skipStart: true, skipStart: true,
buildArgs: ['--debug-prerender'], buildArgs: ['--debug-prerender'],
}) })
...@@ -151,6 +153,64 @@ describe('build-output-prerender', () => { ...@@ -151,6 +153,64 @@ describe('build-output-prerender', () => {
} }
}) })
}) })
})
describe('without a next config file', () => {
describe('without --debug-prerender', () => {
const { next, isTurbopack } = nextTestSetup({
files: path.join(__dirname, 'fixtures/without-config-file'),
skipStart: true,
})
beforeAll(() => next.build())
it('prints no experimental flags', async () => {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(
`"▲ Next.js x.y.z (Turbopack)"`
)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(
`"▲ Next.js x.y.z"`
)
}
})
})
describe('with --debug-prerender', () => {
const { next, isTurbopack } = nextTestSetup({
files: path.join(__dirname, 'fixtures/without-config-file'),
skipStart: true,
buildArgs: ['--debug-prerender'],
})
beforeAll(() => next.build())
it('prints a warning and the customized experimental flags', async () => {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack)
- Experiments (use with caution):
⨯ turbopackMinify (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ enablePrerenderSourceMaps (enabled by \`--debug-prerender\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z
- Experiments (use with caution):
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ enablePrerenderSourceMaps (enabled by \`--debug-prerender\`)"
`)
}
})
})
})
}) })
function getPreambleOutput(cliOutput: string): string { function getPreambleOutput(cliOutput: string): string {
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment