Unverified Commit 14e94e69 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

fix duplicated error logging when start server (#55328)

There're few places calling `loadConfig` to access nextjs config for different purpose, and every of them will do validation of next config scheme and could log the warnings potentially to cause duplicated warnings. To address that issue this PR limit the places when should the warnings be logged in certain places, mainly the `next` command entry. Refactor the API here to make it more explicit

Previous logging redeisgn also might trigger duplicated compilation, for instance you compiled page A but then editing another component it might still displaying page A is recompiled. Now we always display `"Compiled .."` message when there's a recompilation but avoid the unnecessary ones such as initial edge compilor ready but there's no modules inside. Then when it recompiles or recovers from error nextjs server will tell "Compiled .." instead of the specific page which might be not related.

Also refactors a minor issue: When `silent` option is set to `true`, auto recorrect next config option from `loadConfig` API like `traillingSlash` is not working

Closes NEXT-1610
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent 4a6a2ca2
......@@ -58,13 +58,7 @@ async function getResolveRoute(
dir: string,
serverInfo: ServerInfo
): Promise<Resolver> {
const nextConfig = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
process.cwd(),
undefined,
undefined,
true
)
const nextConfig = await loadConfig(PHASE_DEVELOPMENT_SERVER, process.cwd())
const middlewareCfg = {
files: middlewareChunkGroup.filter((f) => /\.[mc]?js$/.test(f)),
matcher: middlewareConfig.matcher,
......
......@@ -140,7 +140,10 @@ async function main() {
// un-necessarily
const config = await loadConfig(
command === 'dev' ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,
dir
dir,
{
silent: false,
}
)
let dirsResult: ReturnType<typeof findPagesDir> | undefined = undefined
......
......@@ -356,7 +356,12 @@ export default async function build(
const config: NextConfigComplete = await nextBuildSpan
.traceChild('load-next-config')
.traceAsyncFn(() => loadConfig(PHASE_PRODUCTION_BUILD, dir))
.traceAsyncFn(() =>
loadConfig(PHASE_PRODUCTION_BUILD, dir, {
// Log for next.config loading process
silent: false,
})
)
NextBuildContext.config = config
let configOutDir = 'out'
......
......@@ -265,7 +265,8 @@ export function watchCompilers(
if (
!status.loading &&
!buildStore.getState().server.loading &&
!buildStore.getState().edgeServer.loading
!buildStore.getState().edgeServer.loading &&
status.totalModulesCount > 0
) {
buildStore.setState({
client: status,
......@@ -281,7 +282,8 @@ export function watchCompilers(
if (
!status.loading &&
!buildStore.getState().client.loading &&
!buildStore.getState().edgeServer.loading
!buildStore.getState().edgeServer.loading &&
status.totalModulesCount > 0
) {
buildStore.setState({
server: status,
......@@ -297,7 +299,8 @@ export function watchCompilers(
if (
!status.loading &&
!buildStore.getState().client.loading &&
!buildStore.getState().server.loading
!buildStore.getState().server.loading &&
status.totalModulesCount > 0
) {
buildStore.setState({
edgeServer: status,
......
......@@ -139,12 +139,15 @@ store.subscribe((state) => {
if (trigger === 'initial') {
trigger = ''
} else if (trigger) {
} else {
if (loadingLogTimer) {
clearTimeout(loadingLogTimer)
loadingLogTimer = null
}
Log.event(`Compiled ${trigger}${timeMessage}${modulesMessage}`)
Log.event(
`Compiled${trigger ? ' ' + trigger : ''}${timeMessage}${modulesMessage}`
)
trigger = ''
}
// Ensure traces are flushed after each compile in development mode
......
......@@ -355,10 +355,7 @@ export async function workerMain(workerData: {
/// load the config because it's not serializable
NextBuildContext.config = await loadConfig(
PHASE_PRODUCTION_BUILD,
NextBuildContext.dir!,
undefined,
undefined,
true
NextBuildContext.dir!
)
NextBuildContext.nextBuildSpan = trace('next-build')
......
......@@ -39,15 +39,7 @@ const handleSessionStop = async () => {
const { eventCliSessionStopped } =
require('../telemetry/events/session-stopped') as typeof import('../telemetry/events/session-stopped')
config =
config ||
(await loadConfig(
PHASE_DEVELOPMENT_SERVER,
dir,
undefined,
undefined,
true
))
config = config || (await loadConfig(PHASE_DEVELOPMENT_SERVER, dir))
let telemetry =
(traceGlobals.get('telemetry') as InstanceType<
......@@ -188,21 +180,16 @@ const nextDev: CliCommand = async (args) => {
const { loadedEnvFiles } = loadEnvConfig(dir, true, console, false)
let expFeatureInfo: string[] = []
config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
dir,
undefined,
undefined,
undefined,
(userConfig) => {
config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir, {
onLoadUserConfig(userConfig) {
const userNextConfigExperimental = getEnabledExperimentalFeatures(
userConfig.experimental
)
expFeatureInfo = userNextConfigExperimental.sort(
(a, b) => a.length - b.length
)
}
)
},
})
let envInfo: string[] = []
if (loadedEnvFiles.length > 0) {
......
......@@ -58,7 +58,7 @@ function getPackageVersion(packageName: string) {
}
async function getNextConfig() {
const config = await loadConfig(PHASE_INFO, dir, undefined, undefined, true)
const config = await loadConfig(PHASE_INFO, dir)
return {
output: config.output ?? 'N/A',
......
......@@ -119,7 +119,9 @@ export async function validateTurboNextConfig({
try {
rawNextConfig = interopDefault(
await loadConfig(PHASE_DEVELOPMENT_SERVER, dir, undefined, true)
await loadConfig(PHASE_DEVELOPMENT_SERVER, dir, {
rawConfig: true,
})
) as NextConfig
if (typeof rawNextConfig === 'function') {
......
......@@ -2,7 +2,6 @@ import { existsSync } from 'fs'
import { basename, extname, join, relative, isAbsolute, resolve } from 'path'
import { pathToFileURL } from 'url'
import findUp from 'next/dist/compiled/find-up'
import chalk from '../lib/chalk'
import * as Log from '../build/output/log'
import { CONFIG_FILES, PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
import {
......@@ -28,7 +27,7 @@ export function warnOptionHasBeenMovedOutOfExperimental(
oldKey: string,
newKey: string,
configFileName: string,
silent = false
silent: boolean
) {
if (config.experimental && oldKey in config.experimental) {
if (!silent) {
......@@ -55,14 +54,15 @@ export function warnOptionHasBeenMovedOutOfExperimental(
function assignDefaults(
dir: string,
userConfig: { [key: string]: any },
silent = false
silent: boolean
) {
const configFileName = userConfig.configFileName
if (!silent && typeof userConfig.exportTrailingSlash !== 'undefined') {
console.warn(
chalk.yellow.bold('Warning: ') +
if (typeof userConfig.exportTrailingSlash !== 'undefined') {
if (!silent) {
Log.warn(
`The "exportTrailingSlash" option has been renamed to "trailingSlash". Please update your ${configFileName}.`
)
)
}
if (typeof userConfig.trailingSlash === 'undefined') {
userConfig.trailingSlash = userConfig.exportTrailingSlash
}
......@@ -701,10 +701,17 @@ function assignDefaults(
export default async function loadConfig(
phase: string,
dir: string,
customConfig?: object | null,
rawConfig?: boolean,
silent?: boolean,
onLoadUserConfig?: (conf: NextConfig) => void
{
customConfig,
rawConfig,
silent = true,
onLoadUserConfig,
}: {
customConfig?: object | null
rawConfig?: boolean
silent?: boolean
onLoadUserConfig?: (conf: NextConfig) => void
} = {}
): Promise<NextConfigComplete> {
if (!process.env.__NEXT_PRIVATE_RENDER_WORKER) {
try {
......@@ -802,7 +809,7 @@ export default async function loadConfig(
const validateResult = validateConfig(userConfig)
if (!silent && validateResult.errors) {
if (validateResult.errors) {
// Only load @segment/ajv-human-errors when invalid config is detected
const { AggregateAjvError } =
require('next/dist/compiled/@segment/ajv-human-errors') as typeof import('next/dist/compiled/@segment/ajv-human-errors')
......@@ -811,7 +818,7 @@ export default async function loadConfig(
})
let shouldExit = false
let messages = [`Invalid ${configFileName} options detected: `]
const messages = [`Invalid ${configFileName} options detected: `]
for (const error of aggregatedAjvErrors) {
messages.push(` ${error.message}`)
......
......@@ -217,9 +217,10 @@ export class NextServer {
loadConfig(
this.options.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,
resolve(this.options.dir || '.'),
this.options.conf,
undefined,
!!this.options._renderWorker
{
customConfig: this.options.conf,
silent: !!this.options._renderWorker,
}
)
)
}
......
......@@ -20,13 +20,7 @@ import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
}
dir = getProjectDir(dir)
const config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
dir,
undefined,
undefined,
true
)
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, dir)
const distDir = path.join(dir, config.distDir || '.next')
const eventsPath = path.join(distDir, '_events.json')
......
......@@ -1154,7 +1154,6 @@ describe.each([[''], ['/docs']])(
...compileTimeStr.match(/Compiled.*? in ([\d.]{1,})\s?(?:s|ms)/i),
]
const [, compileTime, timeUnit] = matches
console.log('compileTime, timeUnit', compileTime, timeUnit)
let compileTimeMs = parseFloat(compileTime[1])
if (timeUnit === 's') {
......
import stripAnsi from 'strip-ansi'
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'next.config.js schema validating - defaultConfig',
{
files: {
'pages/index.js': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exports = (phase, { defaultConfig }) => {
return defaultConfig
}
`,
},
skipDeployment: true,
},
({ next }) => {
it('should validate against defaultConfig', async () => {
const output = stripAnsi(next.cliOutput)
expect(output).not.toContain('Invalid next.config.js options detected')
})
}
)
createNextDescribe(
'next.config.js schema validating - invalid config',
{
files: {
'pages/index.js': `
export default function Page() {
return <p>hello world</p>
}
`,
'next.config.js': `
module.exports = {
badKey: 'badValue'
}
`,
},
skipDeployment: true,
},
({ next, isNextStart }) => {
it('should warn the invalid next config', async () => {
const output = stripAnsi(next.cliOutput)
const warningTimes = output.split('badKey').length - 1
expect(output).toContain('Invalid next.config.js options detected')
expect(output).toContain('badKey')
// for next start and next build we both display the warnings
expect(warningTimes).toBe(isNextStart ? 2 : 1)
})
}
)
module.exports = (phase, { defaultConfig }) => {
return defaultConfig
}
export default function Page() {
return <p>hello world</p>
}
/* eslint-env jest */
import { join } from 'path'
import { nextBuild } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
const appDir = join(__dirname, '../')
describe('next.config.js schema validating', () => {
it('should validate against defaultConfig', async () => {
const result = await nextBuild(appDir, undefined, {
stderr: true,
stdout: true,
})
const output = stripAnsi(result.stderr + result.stdout)
expect(output).not.toContain('Invalid next.config.js options detected')
expect(result.code).toBe(0)
})
})
......@@ -34,20 +34,19 @@ describe('config', () => {
it('Should pass the customConfig correctly', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
customConfig: true,
customConfig: {
customConfigKey: 'customConfigValue',
},
})
expect(config.customConfig).toBe(true)
})
it('Should not pass the customConfig when it is null', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, null)
expect(config.webpack).toBe(null)
expect(config.customConfigKey).toBe('customConfigValue')
})
it('Should assign object defaults deeply to customConfig', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
customConfig: true,
onDemandEntries: { custom: true },
customConfig: {
customConfig: true,
onDemandEntries: { custom: true },
},
})
expect(config.customConfig).toBe(true)
expect(config.onDemandEntries.maxInactiveAge).toBeDefined()
......@@ -55,7 +54,9 @@ describe('config', () => {
it('Should allow setting objects which do not have defaults', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
bogusSetting: { custom: true },
customConfig: {
bogusSetting: { custom: true },
},
})
expect(config.bogusSetting).toBeDefined()
expect(config.bogusSetting.custom).toBe(true)
......@@ -63,7 +64,9 @@ describe('config', () => {
it('Should override defaults for arrays from user arrays', async () => {
const config = await loadConfig(PHASE_DEVELOPMENT_SERVER, null, {
pageExtensions: ['.bogus'],
customConfig: {
pageExtensions: ['.bogus'],
},
})
expect(config.pageExtensions).toEqual(['.bogus'])
})
......
......@@ -11,7 +11,8 @@ describe('warnOptionHasBeenMovedOutOfExperimental', () => {
{},
'skipTrailingSlashRedirect',
'skipTrailingSlashRedirect',
'next.config.js'
'next.config.js',
false
)
warnOptionHasBeenMovedOutOfExperimental(
......@@ -20,7 +21,8 @@ describe('warnOptionHasBeenMovedOutOfExperimental', () => {
},
'skipTrailingSlashRedirect',
'skipTrailingSlashRedirect',
'next.config.js'
'next.config.js',
false
)
expect(spy).not.toBeCalled()
......@@ -35,7 +37,8 @@ describe('warnOptionHasBeenMovedOutOfExperimental', () => {
} as any,
'skipTrailingSlashRedirect',
'skipTrailingSlashRedirect',
'next.config.js'
'next.config.js',
false
)
expect(spy).toHaveBeenCalledWith(
......@@ -53,7 +56,8 @@ describe('warnOptionHasBeenMovedOutOfExperimental', () => {
} as any,
'relay',
'compiler.relay',
'next.config.js'
'next.config.js',
false
)
expect(spy).toHaveBeenCalledWith(
......@@ -72,7 +76,8 @@ describe('warnOptionHasBeenMovedOutOfExperimental', () => {
config,
'skipTrailingSlashRedirect',
'skipTrailingSlashRedirect',
'next.config.js'
'next.config.js',
false
)
expect(config.experimental.skipTrailingSlashRedirect).toBe(true)
......@@ -89,7 +94,8 @@ describe('warnOptionHasBeenMovedOutOfExperimental', () => {
config,
'foo',
'deep.prop.baz',
'next.config.js'
'next.config.js',
false
)
expect(config.experimental.foo).toBe('bar')
......
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