Unverified Commit b2a99181 authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

improve production error message printing (#30065)

* improve production error message printing

* update test cases

* add test case

* improve printing of build errors

* improve types

* fix test cases
parent 094153f9
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import type webpack5 from 'webpack5'
import { Span } from '../trace' import { Span } from '../trace'
export type CompilerResult = { export type CompilerResult = {
errors: string[] errors: webpack5.StatsError[]
warnings: string[] warnings: webpack5.StatsError[]
} }
function generateStats( function generateStats(
result: CompilerResult, result: CompilerResult,
stat: webpack.Stats stat: webpack5.Stats
): CompilerResult { ): CompilerResult {
const { errors, warnings } = stat.toJson('errors-warnings') const { errors, warnings } = stat.toJson({
if (errors.length > 0) { preset: 'errors-warnings',
moduleTrace: true,
})
if (errors && errors.length > 0) {
result.errors.push(...errors) result.errors.push(...errors)
} }
if (warnings.length > 0) { if (warnings && warnings.length > 0) {
result.warnings.push(...warnings) result.warnings.push(...warnings)
} }
...@@ -24,7 +28,7 @@ function generateStats( ...@@ -24,7 +28,7 @@ function generateStats(
// Webpack 5 requires the compiler to be closed (to save caches) // Webpack 5 requires the compiler to be closed (to save caches)
// Webpack 4 does not have this close method so in order to be backwards compatible we check if it exists // Webpack 4 does not have this close method so in order to be backwards compatible we check if it exists
function closeCompiler(compiler: webpack.Compiler | webpack.MultiCompiler) { function closeCompiler(compiler: webpack5.Compiler | webpack5.MultiCompiler) {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
// @ts-ignore Close only exists on the compiler in webpack 5 // @ts-ignore Close only exists on the compiler in webpack 5
return compiler.close((err: any) => (err ? reject(err) : resolve())) return compiler.close((err: any) => (err ? reject(err) : resolve()))
...@@ -36,18 +40,19 @@ export function runCompiler( ...@@ -36,18 +40,19 @@ export function runCompiler(
{ runWebpackSpan }: { runWebpackSpan: Span } { runWebpackSpan }: { runWebpackSpan: Span }
): Promise<CompilerResult> { ): Promise<CompilerResult> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const compiler = webpack(config) const compiler = webpack(config) as unknown as webpack5.Compiler
compiler.run((err: Error, stats: webpack.Stats) => { compiler.run((err, stats) => {
const webpackCloseSpan = runWebpackSpan.traceChild('webpack-close', { const webpackCloseSpan = runWebpackSpan.traceChild('webpack-close', {
name: config.name, name: config.name,
}) })
webpackCloseSpan webpackCloseSpan
.traceAsyncFn(() => closeCompiler(compiler)) .traceAsyncFn(() => closeCompiler(compiler))
.then(() => { .then(() => {
if (!stats) throw new Error('No Stats from webpack')
if (err) { if (err) {
const reason = err?.toString() const reason = err?.stack ?? err?.toString()
if (reason) { if (reason) {
return resolve({ errors: [reason], warnings: [] }) return resolve({ errors: [{ message: reason }], warnings: [] })
} }
return reject(err) return reject(err)
} }
......
...@@ -94,7 +94,7 @@ import { PagesManifest } from './webpack/plugins/pages-manifest-plugin' ...@@ -94,7 +94,7 @@ import { PagesManifest } from './webpack/plugins/pages-manifest-plugin'
import { writeBuildId } from './write-build-id' import { writeBuildId } from './write-build-id'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { NextConfigComplete } from '../server/config-shared' import { NextConfigComplete } from '../server/config-shared'
import isError from '../lib/is-error' import isError, { NextError } from '../lib/is-error'
import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin' import { TelemetryPlugin } from './webpack/plugins/telemetry-plugin'
import { MiddlewareManifest } from './webpack/plugins/middleware-plugin' import { MiddlewareManifest } from './webpack/plugins/middleware-plugin'
...@@ -614,13 +614,13 @@ export default async function build( ...@@ -614,13 +614,13 @@ export default async function build(
result = nextBuildSpan result = nextBuildSpan
.traceChild('format-webpack-messages') .traceChild('format-webpack-messages')
.traceFn(() => formatWebpackMessages(result)) .traceFn(() => formatWebpackMessages(result, true))
if (result.errors.length > 0) { if (result.errors.length > 0) {
// Only keep the first error. Others are often indicative // Only keep the first few errors. Others are often indicative
// of the same problem, but confuse the reader with noise. // of the same problem, but confuse the reader with noise.
if (result.errors.length > 1) { if (result.errors.length > 5) {
result.errors.length = 1 result.errors.length = 5
} }
const error = result.errors.join('\n\n') const error = result.errors.join('\n\n')
...@@ -645,11 +645,17 @@ export default async function build( ...@@ -645,11 +645,17 @@ export default async function build(
error.indexOf('private-next-pages') > -1 || error.indexOf('private-next-pages') > -1 ||
error.indexOf('__next_polyfill__') > -1 error.indexOf('__next_polyfill__') > -1
) { ) {
throw new Error( const err = new Error(
'> webpack config.resolve.alias was incorrectly overridden. https://nextjs.org/docs/messages/invalid-resolve-alias' 'webpack config.resolve.alias was incorrectly overridden. https://nextjs.org/docs/messages/invalid-resolve-alias'
) ) as NextError
err.code = 'INVALID_RESOLVE_ALIAS'
throw err
} }
throw new Error('> Build failed because of webpack errors') const err = new Error(
'Build failed because of webpack errors'
) as NextError
err.code = 'WEBPACK_ERRORS'
throw err
} else { } else {
telemetry.record( telemetry.record(
eventBuildCompleted(pagePaths, { eventBuildCompleted(pagePaths, {
...@@ -1125,7 +1131,7 @@ export default async function build( ...@@ -1125,7 +1131,7 @@ export default async function build(
!customAppGetInitialProps && (!hasNonStaticErrorPage || hasPages404) !customAppGetInitialProps && (!hasNonStaticErrorPage || hasPages404)
if (invalidPages.size > 0) { if (invalidPages.size > 0) {
throw new Error( const err = new Error(
`Build optimization failed: found page${ `Build optimization failed: found page${
invalidPages.size === 1 ? '' : 's' invalidPages.size === 1 ? '' : 's'
} without a React Component as default export in \n${[...invalidPages] } without a React Component as default export in \n${[...invalidPages]
...@@ -1133,7 +1139,9 @@ export default async function build( ...@@ -1133,7 +1139,9 @@ export default async function build(
.join( .join(
'\n' '\n'
)}\n\nSee https://nextjs.org/docs/messages/page-without-valid-component for more info.\n` )}\n\nSee https://nextjs.org/docs/messages/page-without-valid-component for more info.\n`
) ) as NextError
err.code = 'BUILD_OPTIMIZATION_FAILED'
throw err
} }
await writeBuildId(distDir, buildId) await writeBuildId(distDir, buildId)
......
...@@ -235,7 +235,10 @@ export function watchCompilers( ...@@ -235,7 +235,10 @@ export function watchCompilers(
buildStore.setState({ amp: {} }) buildStore.setState({ amp: {} })
const { errors, warnings } = formatWebpackMessages( const { errors, warnings } = formatWebpackMessages(
stats.toJson({ all: false, warnings: true, errors: true }) stats.toJson({
preset: 'error-warnings',
moduleTrace: true,
})
) )
const hasErrors = !!errors?.length const hasErrors = !!errors?.length
......
...@@ -11,11 +11,6 @@ export const base = curry(function base( ...@@ -11,11 +11,6 @@ export const base = curry(function base(
// @ts-ignore TODO webpack 5 typings // @ts-ignore TODO webpack 5 typings
config.target = ctx.isServer ? 'node12.22' : ['web', 'es5'] config.target = ctx.isServer ? 'node12.22' : ['web', 'es5']
// Stop compilation early in a production build when an error is encountered.
// This behavior isn't desirable in development due to how the HMR system
// works, but is a good default for production.
config.bail = ctx.isProduction
// https://webpack.js.org/configuration/devtool/#development // https://webpack.js.org/configuration/devtool/#development
if (ctx.isDevelopment) { if (ctx.isDevelopment) {
if (process.env.__NEXT_TEST_MODE && !process.env.__NEXT_TEST_WITH_DEVTOOL) { if (process.env.__NEXT_TEST_MODE && !process.env.__NEXT_TEST_WITH_DEVTOOL) {
......
...@@ -69,8 +69,17 @@ const nextBuild: cliCommand = (argv) => { ...@@ -69,8 +69,17 @@ const nextBuild: cliCommand = (argv) => {
!args['--no-lint'] !args['--no-lint']
).catch((err) => { ).catch((err) => {
console.error('') console.error('')
console.error('> Build error occurred') if (
printAndExit(err) isError(err) &&
(err.code === 'INVALID_RESOLVE_ALIAS' ||
err.code === 'WEBPACK_ERRORS' ||
err.code === 'BUILD_OPTIMIZATION_FAILED')
) {
printAndExit(`> ${err.message}`)
} else {
console.error('> Build error occurred')
printAndExit(err)
}
}) })
} }
......
export default function formatWebpackMessages(json: any): any export default function formatWebpackMessages(json: any, verbose?: boolean): any
...@@ -32,13 +32,25 @@ function isLikelyASyntaxError(message) { ...@@ -32,13 +32,25 @@ function isLikelyASyntaxError(message) {
} }
// Cleans up webpack error messages. // Cleans up webpack error messages.
function formatMessage(message) { function formatMessage(message, verbose) {
// TODO: Replace this once webpack 5 is stable // TODO: Replace this once webpack 5 is stable
if (typeof message === 'object' && message.message) { if (typeof message === 'object' && message.message) {
message = message =
(message.moduleName ? stripAnsi(message.moduleName) + '\n' : '') + (message.moduleName ? stripAnsi(message.moduleName) + '\n' : '') +
(message.file ? stripAnsi(message.file) + '\n' : '') + (message.file ? stripAnsi(message.file) + '\n' : '') +
message.message message.message +
(message.details && verbose ? '\n' + message.details : '') +
(message.moduleTrace && verbose
? '\n\nImport trace for requested module:' +
message.moduleTrace
.filter(
(trace) =>
!trace.originName.includes('next-client-pages-loader.js')
)
.map((trace) => `\n${trace.originName}`)
.join('')
: '') +
(message.stack && verbose ? '\n' + message.stack : '')
} }
let lines = message.split('\n') let lines = message.split('\n')
...@@ -84,8 +96,6 @@ function formatMessage(message) { ...@@ -84,8 +96,6 @@ function formatMessage(message) {
if (lines.length > 2 && lines[1].trim() === '') { if (lines.length > 2 && lines[1].trim() === '') {
lines.splice(1, 1) lines.splice(1, 1)
} }
// Clean up file name
lines[0] = lines[0].replace(/^(.*) \d+:\d+(?:-\d+)?$/, '$1')
// Cleans up verbose "module not found" messages for files and packages. // Cleans up verbose "module not found" messages for files and packages.
if (lines[1] && lines[1].indexOf('Module not found: ') === 0) { if (lines[1] && lines[1].indexOf('Module not found: ') === 0) {
...@@ -94,7 +104,7 @@ function formatMessage(message) { ...@@ -94,7 +104,7 @@ function formatMessage(message) {
lines[1] lines[1]
.replace('Error: ', '') .replace('Error: ', '')
.replace('Module not found: Cannot find file:', 'Cannot find file:'), .replace('Module not found: Cannot find file:', 'Cannot find file:'),
...lines.slice(2).filter((line) => line.indexOf(' @ ') !== 0), ...lines.slice(2),
] ]
} }
...@@ -132,17 +142,18 @@ function formatMessage(message) { ...@@ -132,17 +142,18 @@ function formatMessage(message) {
return message.trim() return message.trim()
} }
function formatWebpackMessages(json) { function formatWebpackMessages(json, verbose) {
const formattedErrors = json.errors.map(function (message) { const formattedErrors = json.errors.map(function (message) {
return formatMessage(message, true) return formatMessage(message, verbose)
}) })
const formattedWarnings = json.warnings.map(function (message) { const formattedWarnings = json.warnings.map(function (message) {
return formatMessage(message, false) return formatMessage(message, verbose)
}) })
const result = { errors: formattedErrors, warnings: formattedWarnings } const result = { errors: formattedErrors, warnings: formattedWarnings }
if (result.errors.some(isLikelyASyntaxError)) { if (!verbose && result.errors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them. // If there are any syntax errors, show just them.
result.errors = result.errors.filter(isLikelyASyntaxError) result.errors = result.errors.filter(isLikelyASyntaxError)
result.warnings = []
} }
return result return result
} }
......
// We allow some additional attached properties for Errors // We allow some additional attached properties for Errors
interface NextError extends Error { export interface NextError extends Error {
type?: string type?: string
page?: string page?: string
code?: string | number code?: string | number
......
...@@ -14,16 +14,7 @@ export default { ...@@ -14,16 +14,7 @@ export default {
env: { env: {
customVar: 'hello', customVar: 'hello',
}, },
webpack(config, { dev, buildId, webpack }) { webpack(config, { buildId, webpack }) {
if (dev) {
if (config.bail !== false) {
throw new Error('Wrong bail value for development!')
}
} else {
if (config.bail !== true) {
throw new Error('Wrong bail value for production!')
}
}
config.plugins.push( config.plugins.push(
new webpack.DefinePlugin({ new webpack.DefinePlugin({
'process.env.CONFIG_BUILD_ID': JSON.stringify(buildId), 'process.env.CONFIG_BUILD_ID': JSON.stringify(buildId),
......
...@@ -14,16 +14,7 @@ module.exports = { ...@@ -14,16 +14,7 @@ module.exports = {
env: { env: {
customVar: 'hello', customVar: 'hello',
}, },
webpack(config, { dev, buildId, webpack }) { webpack(config, { buildId, webpack }) {
if (dev) {
if (config.bail !== false) {
throw new Error('Wrong bail value for development!')
}
} else {
if (config.bail !== true) {
throw new Error('Wrong bail value for production!')
}
}
config.plugins.push( config.plugins.push(
new webpack.DefinePlugin({ new webpack.DefinePlugin({
'process.env.CONFIG_BUILD_ID': JSON.stringify(buildId), 'process.env.CONFIG_BUILD_ID': JSON.stringify(buildId),
......
...@@ -99,8 +99,10 @@ describe('Build Error Tests for basePath', () => { ...@@ -99,8 +99,10 @@ describe('Build Error Tests for basePath', () => {
await indexPage.restore() await indexPage.restore()
expect(stderr).toContain( expect(stderr).toContain(
"Error: Can't resolve '../public/foo/test-rect-broken.jpg" "Module not found: Can't resolve '../public/foo/test-rect-broken.jpg"
) )
// should contain the importing module
expect(stderr).toContain('./pages/static-img.js')
}) })
}) })
describe('Static Image Component Tests for basePath', () => { describe('Static Image Component Tests for basePath', () => {
......
...@@ -87,8 +87,10 @@ describe('Build Error Tests', () => { ...@@ -87,8 +87,10 @@ describe('Build Error Tests', () => {
await indexPage.restore() await indexPage.restore()
expect(stderr).toContain( expect(stderr).toContain(
"Error: Can't resolve '../public/foo/test-rect-broken.jpg" "Module not found: Can't resolve '../public/foo/test-rect-broken.jpg"
) )
// should contain the importing module
expect(stderr).toContain('./pages/static-img.js')
}) })
}) })
describe('Static Image Component Tests', () => { describe('Static Image Component Tests', () => {
......
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