rsnext/packages/next/build/webpack/plugins/wellknown-errors-plugin/parseNotFoundError.ts
Tim Neutkens 405e42e41e
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
2020-08-05 19:11:35 +00:00

56 lines
1.6 KiB
TypeScript

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
}
}