Unverified Commit e173967b authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

[Fast Refresh] New Compile Error Overlay (#12543)

parent ab781117
......@@ -229,8 +229,8 @@ export default async function getBaseWebpackConfig(
typeScriptPath && (await fileExists(tsConfigPath))
)
const ignoreTypeScriptErrors = dev
? config.typescript?.ignoreDevErrors
: config.typescript?.ignoreBuildErrors
? Boolean(isReactRefreshEnabled || config.typescript?.ignoreDevErrors)
: Boolean(config.typescript?.ignoreBuildErrors)
let jsConfig
// jsconfig is a subset of tsconfig
......
......@@ -64,28 +64,17 @@ export default function connect(options) {
if (process.env.__NEXT_FAST_REFRESH) {
DevOverlay.register()
}
// We need to keep track of if there has been a runtime error.
// Essentially, we cannot guarantee application state was not corrupted by the
// runtime error. To prevent confusing behavior, we forcibly reload the entire
// application. This is handled below when we are notified of a compile (code
// change).
// See https://github.com/facebook/create-react-app/issues/3096
ErrorOverlay.startReportingRuntimeErrors({
onError: function() {
if (process.env.__NEXT_FAST_REFRESH) {
return
}
hadRuntimeError = true
},
})
if (module.hot && typeof module.hot.dispose === 'function') {
module.hot.dispose(function() {
// TODO: why do we need this?
ErrorOverlay.stopReportingRuntimeErrors()
} else {
// We need to keep track of if there has been a runtime error.
// Essentially, we cannot guarantee application state was not corrupted by the
// runtime error. To prevent confusing behavior, we forcibly reload the entire
// application. This is handled below when we are notified of a compile (code
// change).
// See https://github.com/facebook/create-react-app/issues/3096
ErrorOverlay.startReportingRuntimeErrors({
onError: function() {
hadRuntimeError = true
},
})
}
......@@ -215,7 +204,11 @@ function handleErrors(errors) {
})
// Only show the first error.
ErrorOverlay.reportBuildError(formatted.errors[0])
if (process.env.__NEXT_FAST_REFRESH) {
DevOverlay.onBuildError(formatted.errors[0])
} else {
ErrorOverlay.reportBuildError(formatted.errors[0])
}
// Also log them to the console.
if (typeof console !== 'undefined' && typeof console.error === 'function') {
......@@ -235,15 +228,18 @@ function handleErrors(errors) {
}
function tryDismissErrorOverlay() {
if (!hasCompileErrors) {
ErrorOverlay.dismissBuildError()
if (!process.env.__NEXT_FAST_REFRESH) {
if (!hasCompileErrors) {
ErrorOverlay.dismissBuildError()
}
}
}
function onFastRefresh(hasUpdates) {
tryDismissErrorOverlay()
if (hasUpdates) {
if (process.env.__NEXT_FAST_REFRESH) {
if (process.env.__NEXT_FAST_REFRESH) {
DevOverlay.onBuildOk()
if (hasUpdates) {
DevOverlay.onRefresh()
}
}
......@@ -287,6 +283,10 @@ function processMessage(e) {
return handleSuccess()
}
case 'typeChecked': {
if (process.env.__NEXT_FAST_REFRESH) {
break
}
const eventId = ++hmrEventCount
const [{ errors }] = obj.data
......
import reactDevOverlayMiddleware from '@next/react-dev-overlay/lib/middleware'
import { NextHandleFunction } from 'connect'
import { IncomingMessage, ServerResponse } from 'http'
import WebpackDevMiddleware from 'next/dist/compiled/webpack-dev-middleware'
......@@ -23,7 +24,6 @@ import { route } from '../next-server/server/router'
import errorOverlayMiddleware from './lib/error-overlay-middleware'
import { findPageFile } from './lib/find-page-file'
import onDemandEntryHandler, { normalizePage } from './on-demand-entry-handler'
import reactDevOverlayMiddleware from '@next/react-dev-overlay/lib/middleware'
export async function renderScriptError(res: ServerResponse, error: Error) {
// Asks CDNs and others to not to cache the errored page
......@@ -364,8 +364,10 @@ export default class HotReloader {
async prepareBuildTools(multiCompiler: webpack.MultiCompiler) {
const tsConfigPath = join(this.dir, 'tsconfig.json')
const useTypeScript = await fileExists(tsConfigPath)
const ignoreTypeScriptErrors =
this.config.typescript && this.config.typescript.ignoreDevErrors
const ignoreTypeScriptErrors = Boolean(
this.config.experimental.reactRefresh === true ||
this.config.typescript?.ignoreDevErrors
)
watchCompilers(
multiCompiler.compilers[0],
......
......@@ -71,10 +71,18 @@ function unregister() {
window.removeEventListener('unhandledrejection', onUnhandledRejection)
}
function onBuildOk() {
Bus.emit({ type: Bus.TYPE_BUILD_OK })
}
function onBuildError(message: string) {
Bus.emit({ type: Bus.TYPE_BUILD_ERROR, message })
}
function onRefresh() {
Bus.emit({ type: Bus.TYPE_REFFRESH })
}
export { getNodeError } from './internal/helpers/nodeStackFrames'
export { default as ReactDevOverlay } from './internal/ReactDevOverlay'
export { register, unregister, onRefresh }
export { onBuildOk, onBuildError, register, unregister, onRefresh }
......@@ -2,6 +2,7 @@ import * as React from 'react'
import * as Bus from './bus'
import { ShadowPortal } from './components/ShadowPortal'
import { Errors, SupportedErrorEvent } from './container/Errors'
import { BuildError } from './container/BuildError'
import { ErrorBoundary } from './ErrorBoundary'
import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles'
......@@ -9,11 +10,21 @@ import { CssReset } from './styles/CssReset'
type OverlayState = {
nextId: number
buildError: string | null
errors: SupportedErrorEvent[]
}
function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
switch (ev.type) {
case Bus.TYPE_BUILD_OK: {
return { ...state, buildError: null }
}
case Bus.TYPE_BUILD_ERROR: {
return { ...state, buildError: ev.message }
}
case Bus.TYPE_REFFRESH: {
return { ...state, buildError: null, errors: [] }
}
case Bus.TYPE_UNHANDLED_ERROR:
case Bus.TYPE_UNHANDLED_REJECTION: {
return {
......@@ -22,9 +33,6 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
errors: [...state.errors, { id: state.nextId, event: ev }],
}
}
case Bus.TYPE_REFFRESH: {
return { ...state, errors: [] }
}
default: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = ev
......@@ -36,7 +44,7 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
function ReactDevOverlay({ children }) {
const [state, dispatch] = React.useReducer<
React.Reducer<OverlayState, Bus.BusEvent>
>(reducer, { nextId: 1, errors: [] })
>(reducer, { nextId: 1, buildError: null, errors: [] })
React.useEffect(() => {
Bus.on(dispatch)
......@@ -52,18 +60,28 @@ function ReactDevOverlay({ children }) {
[]
)
const hasBuildError = state.buildError != null
const hasRuntimeErrors = Boolean(state.errors.length)
const isMounted = hasBuildError || hasRuntimeErrors
return (
<React.Fragment>
<ErrorBoundary onError={onComponentError}>
{children ?? null}
</ErrorBoundary>
{state.errors.length ? (
{isMounted ? (
<ShadowPortal>
<CssReset />
<Base />
<ComponentStyles />
<Errors errors={state.errors} />
{hasBuildError ? (
<BuildError message={state.buildError} />
) : hasRuntimeErrors ? (
<Errors errors={state.errors} />
) : (
undefined
)}
</ShadowPortal>
) : (
undefined
......
import { StackFrame } from 'stacktrace-parser'
export const TYPE_BUILD_OK = 'build-ok'
export const TYPE_BUILD_ERROR = 'build-error'
export const TYPE_REFFRESH = 'fast-refresh'
export const TYPE_UNHANDLED_ERROR = 'unhandled-error'
export const TYPE_UNHANDLED_REJECTION = 'unhandled-rejection'
export type BuildOk = { type: typeof TYPE_BUILD_OK }
export type BuildError = {
type: typeof TYPE_BUILD_ERROR
message: string
}
export type FastRefresh = { type: typeof TYPE_REFFRESH }
export type UnhandledError = {
type: typeof TYPE_UNHANDLED_ERROR
......@@ -15,7 +22,13 @@ export type UnhandledRejection = {
reason: Error
frames: StackFrame[]
}
export type BusEvent = UnhandledError | UnhandledRejection | FastRefresh
export type BusEvent =
| BuildOk
| BuildError
| FastRefresh
| UnhandledError
| UnhandledRejection
export type BusEventHandler = (ev: BusEvent) => void
let handlers: Set<BusEventHandler> = new Set()
......
......@@ -3,11 +3,12 @@ import allyTrap from 'ally.js/maintain/tab-focus'
import * as React from 'react'
import { lock, unlock } from './body-locker'
export type OverlayProps = { className?: string }
export type OverlayProps = { className?: string; fixed?: boolean }
const Overlay: React.FC<OverlayProps> = function Overlay({
className,
children,
fixed,
}) {
React.useEffect(() => {
lock()
......@@ -36,7 +37,10 @@ const Overlay: React.FC<OverlayProps> = function Overlay({
return (
<div data-nextjs-dialog-overlay className={className} ref={onOverlay}>
<div data-nextjs-dialog-backdrop />
<div
data-nextjs-dialog-backdrop
data-nextjs-dialog-backdrop-fixed={fixed ? true : undefined}
/>
{children}
</div>
)
......
......@@ -27,6 +27,12 @@ const styles = css`
pointer-events: all;
z-index: -1;
}
[data-nextjs-dialog-backdrop-fixed] {
cursor: not-allowed;
-webkit-backdrop-filter: blur(8px);
backdrop-filter: blur(8px);
}
`
export { styles }
import Anser from 'anser'
import * as React from 'react'
export type TerminalProps = { content: string }
export const Terminal: React.FC<TerminalProps> = function Terminal({
content,
}) {
const decoded = React.useMemo(() => {
return Anser.ansiToJson(content, {
json: true,
use_classes: true,
remove_empty: true,
})
}, [content])
return (
<div data-nextjs-terminal>
<pre>
{decoded.map((entry, index) => (
<span
key={`terminal-entry-${index}`}
style={{
color: entry.fg ? `var(--color-${entry.fg})` : undefined,
...(entry.decoration === 'bold'
? { fontWeight: 800 }
: entry.decoration === 'italic'
? { fontStyle: 'italic' }
: undefined),
}}
>
{entry.content}
</span>
))}
</pre>
</div>
)
}
import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-terminal] {
border-radius: 0.3rem;
background-color: var(--color-ansi-bg);
color: var(--color-ansi-fg);
}
[data-nextjs-terminal]::selection,
[data-nextjs-terminal] *::selection {
background-color: var(--color-ansi-selection);
}
[data-nextjs-terminal] * {
color: inherit;
background-color: transparent;
font-family: var(--font-stack-monospace);
}
[data-nextjs-terminal] > * {
margin: 0;
padding: 0.5rem;
}
[data-nextjs-terminal] pre {
white-space: pre-wrap;
word-break: break-word;
}
`
export { styles }
import * as React from 'react'
import {
Dialog,
DialogBody,
DialogContent,
DialogHeader,
} from '../components/Dialog'
import { Overlay } from '../components/Overlay'
import { Terminal } from '../components/Terminal'
import { noop as css } from '../helpers/noop-template'
export type BuildErrorProps = { message: string }
export const BuildError: React.FC<BuildErrorProps> = function BuildError({
message,
}) {
const noop = React.useCallback(() => {}, [])
return (
<Overlay fixed>
<Dialog
type="error"
aria-labelledby="nextjs__container_build_error_label"
aria-describedby="nextjs__container_build_error_desc"
onClose={noop}
>
<DialogContent>
<DialogHeader className="nextjs-container-build-error-header">
<h4 id="nextjs__container_build_error_label">Failed to compile</h4>
</DialogHeader>
<DialogBody className="nextjs-container-build-error-body">
<Terminal content={message} />
<footer>
<p id="nextjs__container_build_error_desc">
<small>
This error occured during the build process and cannot be
dismissed.
</small>
</p>
</footer>
</DialogBody>
</DialogContent>
</Dialog>
</Overlay>
)
}
export const styles = css`
.nextjs-container-build-error-header > h4 {
line-height: 1.5;
margin: 0;
margin-top: 1rem;
}
.nextjs-container-build-error-body,
.nextjs-container-build-error-body footer {
margin-top: 1.5rem;
}
.nextjs-container-build-error-body small {
color: #757575;
}
`
......@@ -3,7 +3,9 @@ import { styles as codeFrame } from '../components/CodeFrame/styles'
import { styles as dialog } from '../components/Dialog'
import { styles as leftRightDialogHeader } from '../components/LeftRightDialogHeader/styles'
import { styles as overlay } from '../components/Overlay/styles'
import { styles as terminal } from '../components/Terminal/styles'
import { styles as toast } from '../components/Toast'
import { styles as buildErrorStyles } from '../container/BuildError'
import { styles as containerErrorStyles } from '../container/Errors'
import { styles as containerRuntimeErrorStyles } from '../container/RuntimeError'
import { noop as css } from '../helpers/noop-template'
......@@ -18,7 +20,9 @@ export function ComponentStyles() {
${dialog}
${leftRightDialogHeader}
${codeFrame}
${terminal}
${buildErrorStyles}
${containerErrorStyles}
${containerRuntimeErrorStyles}
`,
......
......@@ -86,7 +86,9 @@ test('can recover from a syntax error without losing state', async () => {
).toBe('1')
await session.patch('index.js', `export default () => <div/`)
expect(await session.getOverlayContent()).toMatch('Failed to compile')
expect(await session.hasRedbox(true)).toBe(true)
expect(await session.getRedboxSource()).toMatch('SyntaxError')
await session.patch(
'index.js',
......
......@@ -106,16 +106,6 @@ export async function sandbox(id = nanoid()) {
)
}
},
async getOverlayContent() {
await browser.waitForElementByCss('iframe', 10000)
const hasIframe = await browser.hasElementByCssSelector('iframe')
if (!hasIframe) {
throw new Error('Unable to find overlay')
}
return browser.eval(
`document.querySelector('iframe').contentWindow.document.body.innerHTML`
)
},
async hasRedbox(expected = false) {
let attempts = 3
do {
......@@ -124,7 +114,9 @@ export async function sandbox(id = nanoid()) {
[].slice
.call(document.querySelectorAll('nextjs-portal'))
.find(p =>
p.shadowRoot.querySelector('#nextjs__container_errors_label')
p.shadowRoot.querySelector(
'#nextjs__container_errors_label, #nextjs__container_build_error_label'
)
)
)
})
......@@ -144,10 +136,14 @@ export async function sandbox(id = nanoid()) {
const portal = [].slice
.call(document.querySelectorAll('nextjs-portal'))
.find(p =>
p.shadowRoot.querySelector('#nextjs__container_errors_label')
p.shadowRoot.querySelector(
'#nextjs__container_errors_label, #nextjs__container_build_error_label'
)
)
const root = portal.shadowRoot
return root.querySelector('[data-nextjs-codeframe]').innerText
return root.querySelector(
'[data-nextjs-codeframe], [data-nextjs-terminal]'
).innerText
})
},
},
......
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