Unverified Commit 405e42e4 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Enhance module not found error (#15860)

Adds handling for module not found errors exposed by webpack. This ensures you see the actual stack line and code instead of a short message where you don't know where to go.

### Previous

<img width="794" alt="Screen Shot 2020-08-05 at 18 02 06" src="https://user-images.githubusercontent.com/6324199/89435935-d5542c00-d745-11ea-9ca7-c67f553364f9.png">


### New

<img width="769" alt="Screen Shot 2020-08-05 at 14 20 23" src="https://user-images.githubusercontent.com/6324199/89412212-f6595480-d726-11ea-81a3-398ab7036338.png">


Fixes #14711
parent 46488fbc
......@@ -4,14 +4,27 @@ import { getModuleBuildError } from './webpackModuleError'
export class WellKnownErrorsPlugin {
apply(compiler: Compiler) {
compiler.hooks.compilation.tap('WellKnownErrorsPlugin', (compilation) => {
compilation.hooks.seal.tap('WellKnownErrorsPlugin', () => {
if (compilation.errors?.length) {
compilation.errors = compilation.errors.map((err) => {
const moduleError = getModuleBuildError(compilation, err)
return moduleError === false ? err : moduleError
})
compilation.hooks.afterSeal.tapPromise(
'WellKnownErrorsPlugin',
async () => {
if (compilation.errors?.length) {
compilation.errors = await Promise.all(
compilation.errors.map(async (err) => {
try {
const moduleError = await getModuleBuildError(
compilation,
err
)
return moduleError === false ? err : moduleError
} catch (e) {
console.log(e)
return err
}
})
)
}
}
})
)
})
}
}
import Chalk from 'next/dist/compiled/chalk'
import { SimpleWebpackError } from './simpleWebpackError'
import { createOriginalStackFrame } from '@next/react-dev-overlay/lib/middleware'
const chalk = new Chalk.constructor({ enabled: true })
export async function getNotFoundError(
compilation: any,
input: any,
fileName: string
) {
if (input.name !== 'ModuleNotFoundError') {
return false
}
const loc = input.loc
? input.loc
: input.dependencies.map((d: any) => d.loc).filter(Boolean)[0]
const originalSource = input.module.originalSource()
try {
const result = await createOriginalStackFrame({
line: loc.start.line,
column: loc.start.column,
source: originalSource,
rootDirectory: compilation.options.context,
frame: {},
})
// If we could not result the original location we still need to show the existing error
if (!result) {
return input
}
const errorMessage = input.error.message
.replace(/ in '.*?'/, '')
.replace(/Can't resolve '(.*)'/, `Can't resolve '${chalk.green('$1')}'`)
const message =
chalk.red.bold('Module not found') +
`: ${errorMessage}` +
'\n' +
result.originalCodeFrame
return new SimpleWebpackError(
`${chalk.cyan(fileName)}:${chalk.yellow(
result.originalStackFrame.lineNumber?.toString() ?? ''
)}:${chalk.yellow(result.originalStackFrame.column?.toString() ?? '')}`,
message
)
} catch (err) {
console.log('Failed to parse source map:', err)
// Don't fail on failure to resolve sourcemaps
return input
}
}
......@@ -5,6 +5,7 @@ import { compilation as CompilationType } from 'webpack'
import { getBabelError } from './parseBabel'
import { getCssError } from './parseCss'
import { getScssError } from './parseScss'
import { getNotFoundError } from './parseNotFoundError'
import { SimpleWebpackError } from './simpleWebpackError'
function getFileData(
......@@ -40,14 +41,15 @@ function getFileData(
return ['<unknown>', null]
}
export function getModuleBuildError(
export async function getModuleBuildError(
compilation: CompilationType.Compilation,
input: any
): SimpleWebpackError | false {
): Promise<SimpleWebpackError | false> {
if (
!(
typeof input === 'object' &&
input?.name === 'ModuleBuildError' &&
(input?.name === 'ModuleBuildError' ||
input?.name === 'ModuleNotFoundError') &&
Boolean(input.module) &&
input.error instanceof Error
)
......@@ -58,6 +60,15 @@ export function getModuleBuildError(
const err: Error = input.error
const [sourceFilename, sourceContent] = getFileData(compilation, input.module)
const notFoundError = await getNotFoundError(
compilation,
input,
sourceFilename
)
if (notFoundError !== false) {
return notFoundError
}
const babel = getBabelError(sourceFilename, err)
if (babel !== false) {
return babel
......
......@@ -67,6 +67,103 @@ function getSourcePath(source: string) {
return source
}
async function findOriginalSourcePositionAndContent(
webpackSource: any,
position: { line: number; column: number | null }
) {
const consumer = await new SourceMapConsumer(webpackSource.map())
try {
const sourcePosition: NullableMappedPosition = consumer.originalPositionFor(
{
line: position.line,
column: position.column ?? 0,
}
)
if (!sourcePosition.source) {
return null
}
const sourceContent: string | null =
consumer.sourceContentFor(
sourcePosition.source,
/* returnNullOnMissing */ true
) ?? null
return {
sourcePosition,
sourceContent,
}
} finally {
consumer.destroy()
}
}
export async function createOriginalStackFrame({
line,
column,
source,
rootDirectory,
frame,
}: {
line: number
column: number | null
source: any
rootDirectory: string
frame: any
}): Promise<OriginalStackFrameResponse | null> {
const result = await findOriginalSourcePositionAndContent(source, {
line,
column,
})
if (result === null) {
return null
}
const { sourcePosition, sourceContent } = result
if (!sourcePosition.source) {
return null
}
const filePath = path.resolve(
rootDirectory,
getSourcePath(sourcePosition.source)
)
const originalFrame: StackFrame = {
file: sourceContent
? path.relative(rootDirectory, filePath)
: sourcePosition.source,
lineNumber: sourcePosition.line,
column: sourcePosition.column,
methodName: frame.methodName, // TODO: resolve original method name (?)
arguments: [],
}
const originalCodeFrame: string | null =
!(originalFrame.file?.includes('node_modules') ?? true) &&
sourceContent &&
sourcePosition.line
? (codeFrameColumns(
sourceContent,
{
start: {
line: sourcePosition.line,
column: sourcePosition.column ?? 0,
},
},
{ forceColor: true }
) as string)
: null
return {
originalStackFrame: originalFrame,
originalCodeFrame,
}
}
function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
async function getSourceById(
isServerSide: boolean,
......@@ -170,69 +267,31 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
frameColumn = null
}
let pos: NullableMappedPosition
let posSourceContent: string | null = null
try {
const consumer = await new SourceMapConsumer(source.map())
pos = consumer.originalPositionFor({
const originalStackFrameResponse = await createOriginalStackFrame({
line: frameLine,
column: frameColumn ?? 0,
column: frameColumn,
source,
frame,
rootDirectory: options.rootDirectory,
})
if (pos.source) {
posSourceContent =
consumer.sourceContentFor(
pos.source,
/* returnNullOnMissing */ true
) ?? null
if (originalStackFrameResponse === null) {
res.statusCode = 204
res.write('No Content')
return res.end()
}
consumer.destroy()
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.write(Buffer.from(JSON.stringify(originalStackFrameResponse)))
return res.end()
} catch (err) {
console.log('Failed to parse source map:', err)
res.statusCode = 500
res.write('Internal Server Error')
return res.end()
}
if (pos.source == null) {
res.statusCode = 204
res.write('No Content')
return res.end()
}
const filePath = path.resolve(
options.rootDirectory,
getSourcePath(pos.source)
)
const originalFrame: StackFrame = {
file: posSourceContent
? path.relative(options.rootDirectory, filePath)
: pos.source,
lineNumber: pos.line,
column: pos.column,
methodName: frame.methodName, // TODO: resolve original method name (?)
arguments: [],
}
const originalCodeFrame: string | null =
!(originalFrame.file?.includes('node_modules') ?? true) &&
posSourceContent &&
pos.line
? (codeFrameColumns(
posSourceContent,
{ start: { line: pos.line, column: pos.column ?? 0 } },
{ forceColor: true }
) as string)
: null
const o: OriginalStackFrameResponse = {
originalStackFrame: originalFrame,
originalCodeFrame,
}
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.write(Buffer.from(JSON.stringify(o)))
return res.end()
} else if (pathname === '/__nextjs_launch-editor') {
const frame = (query as unknown) as StackFrame
......
......@@ -678,6 +678,41 @@ test('unterminated JSX', async () => {
await cleanup()
})
test('Module not found', async () => {
const [session, cleanup] = await sandbox()
await session.patch(
'index.js',
`
import Comp from 'b'
export default () => {
return (
<div>
<Comp>lol</Comp>
</div>
)
}
`
)
expect(await session.hasRedbox(true)).toBe(true)
const source = await session.getRedboxSource()
expect(source).toMatchInlineSnapshot(`
"./index.js:2:6
Module not found: Can't resolve 'b'
1 |
> 2 | import Comp from 'b'
| ^
3 |
4 | export default () => {
5 | return ("
`)
await cleanup()
})
test('conversion to class component (1)', async () => {
const [session, cleanup] = await sandbox()
......
......@@ -40,6 +40,7 @@ export async function sandbox(
return [
{
sandboxDirectory,
async write(fileName, content) {
// Update the file on filesystem
const fullFileName = path.join(sandboxDirectory, fileName)
......
......@@ -56,7 +56,7 @@ describe('TypeScript Features', () => {
const found = await check(
() => output,
/Module not found: Can't resolve 'components\/worldd' in/,
/Module not found: Can't resolve 'components\/worldd'/,
false
)
await fs.writeFile(basicPage, contents)
......
......@@ -73,7 +73,7 @@ describe('TypeScript Features', () => {
const found = await check(
() => output,
/Module not found: Can't resolve '@c\/worldd' in/,
/Module not found: Can't resolve '@c\/worldd'/,
false
)
await fs.writeFile(basicPage, contents)
......
......@@ -7784,11 +7784,6 @@ he@1.1.1:
resolved "https://registry.yarnpkg.com/he/-/he-1.1.1.tgz#93410fd21b009735151f8868c2f271f3427e23fd"
integrity sha1-k0EP0hsAlzUVH4howvJx80J+I/0=
he@1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/he/-/he-1.1.1.tgz#93410fd21b009735151f8868c2f271f3427e23fd"
integrity sha1-k0EP0hsAlzUVH4howvJx80J+I/0=
header-case@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/header-case/-/header-case-1.0.1.tgz#9535973197c144b09613cd65d317ef19963bd02d"
......
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