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( ...@@ -229,8 +229,8 @@ export default async function getBaseWebpackConfig(
typeScriptPath && (await fileExists(tsConfigPath)) typeScriptPath && (await fileExists(tsConfigPath))
) )
const ignoreTypeScriptErrors = dev const ignoreTypeScriptErrors = dev
? config.typescript?.ignoreDevErrors ? Boolean(isReactRefreshEnabled || config.typescript?.ignoreDevErrors)
: config.typescript?.ignoreBuildErrors : Boolean(config.typescript?.ignoreBuildErrors)
let jsConfig let jsConfig
// jsconfig is a subset of tsconfig // jsconfig is a subset of tsconfig
......
...@@ -64,28 +64,17 @@ export default function connect(options) { ...@@ -64,28 +64,17 @@ export default function connect(options) {
if (process.env.__NEXT_FAST_REFRESH) { if (process.env.__NEXT_FAST_REFRESH) {
DevOverlay.register() DevOverlay.register()
} } else {
// We need to keep track of if there has been a runtime error.
// We need to keep track of if there has been a runtime error. // Essentially, we cannot guarantee application state was not corrupted by the
// Essentially, we cannot guarantee application state was not corrupted by the // runtime error. To prevent confusing behavior, we forcibly reload the entire
// runtime error. To prevent confusing behavior, we forcibly reload the entire // application. This is handled below when we are notified of a compile (code
// application. This is handled below when we are notified of a compile (code // change).
// change). // See https://github.com/facebook/create-react-app/issues/3096
// See https://github.com/facebook/create-react-app/issues/3096 ErrorOverlay.startReportingRuntimeErrors({
ErrorOverlay.startReportingRuntimeErrors({ onError: function() {
onError: function() { hadRuntimeError = true
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()
}) })
} }
...@@ -215,7 +204,11 @@ function handleErrors(errors) { ...@@ -215,7 +204,11 @@ function handleErrors(errors) {
}) })
// Only show the first error. // 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. // Also log them to the console.
if (typeof console !== 'undefined' && typeof console.error === 'function') { if (typeof console !== 'undefined' && typeof console.error === 'function') {
...@@ -235,15 +228,18 @@ function handleErrors(errors) { ...@@ -235,15 +228,18 @@ function handleErrors(errors) {
} }
function tryDismissErrorOverlay() { function tryDismissErrorOverlay() {
if (!hasCompileErrors) { if (!process.env.__NEXT_FAST_REFRESH) {
ErrorOverlay.dismissBuildError() if (!hasCompileErrors) {
ErrorOverlay.dismissBuildError()
}
} }
} }
function onFastRefresh(hasUpdates) { function onFastRefresh(hasUpdates) {
tryDismissErrorOverlay() tryDismissErrorOverlay()
if (hasUpdates) { if (process.env.__NEXT_FAST_REFRESH) {
if (process.env.__NEXT_FAST_REFRESH) { DevOverlay.onBuildOk()
if (hasUpdates) {
DevOverlay.onRefresh() DevOverlay.onRefresh()
} }
} }
...@@ -287,6 +283,10 @@ function processMessage(e) { ...@@ -287,6 +283,10 @@ function processMessage(e) {
return handleSuccess() return handleSuccess()
} }
case 'typeChecked': { case 'typeChecked': {
if (process.env.__NEXT_FAST_REFRESH) {
break
}
const eventId = ++hmrEventCount const eventId = ++hmrEventCount
const [{ errors }] = obj.data const [{ errors }] = obj.data
......
import reactDevOverlayMiddleware from '@next/react-dev-overlay/lib/middleware'
import { NextHandleFunction } from 'connect' import { NextHandleFunction } from 'connect'
import { IncomingMessage, ServerResponse } from 'http' import { IncomingMessage, ServerResponse } from 'http'
import WebpackDevMiddleware from 'next/dist/compiled/webpack-dev-middleware' import WebpackDevMiddleware from 'next/dist/compiled/webpack-dev-middleware'
...@@ -23,7 +24,6 @@ import { route } from '../next-server/server/router' ...@@ -23,7 +24,6 @@ import { route } from '../next-server/server/router'
import errorOverlayMiddleware from './lib/error-overlay-middleware' import errorOverlayMiddleware from './lib/error-overlay-middleware'
import { findPageFile } from './lib/find-page-file' import { findPageFile } from './lib/find-page-file'
import onDemandEntryHandler, { normalizePage } from './on-demand-entry-handler' 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) { export async function renderScriptError(res: ServerResponse, error: Error) {
// Asks CDNs and others to not to cache the errored page // Asks CDNs and others to not to cache the errored page
...@@ -364,8 +364,10 @@ export default class HotReloader { ...@@ -364,8 +364,10 @@ export default class HotReloader {
async prepareBuildTools(multiCompiler: webpack.MultiCompiler) { async prepareBuildTools(multiCompiler: webpack.MultiCompiler) {
const tsConfigPath = join(this.dir, 'tsconfig.json') const tsConfigPath = join(this.dir, 'tsconfig.json')
const useTypeScript = await fileExists(tsConfigPath) const useTypeScript = await fileExists(tsConfigPath)
const ignoreTypeScriptErrors = const ignoreTypeScriptErrors = Boolean(
this.config.typescript && this.config.typescript.ignoreDevErrors this.config.experimental.reactRefresh === true ||
this.config.typescript?.ignoreDevErrors
)
watchCompilers( watchCompilers(
multiCompiler.compilers[0], multiCompiler.compilers[0],
......
...@@ -71,10 +71,18 @@ function unregister() { ...@@ -71,10 +71,18 @@ function unregister() {
window.removeEventListener('unhandledrejection', onUnhandledRejection) 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() { function onRefresh() {
Bus.emit({ type: Bus.TYPE_REFFRESH }) Bus.emit({ type: Bus.TYPE_REFFRESH })
} }
export { getNodeError } from './internal/helpers/nodeStackFrames' export { getNodeError } from './internal/helpers/nodeStackFrames'
export { default as ReactDevOverlay } from './internal/ReactDevOverlay' 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' ...@@ -2,6 +2,7 @@ import * as React from 'react'
import * as Bus from './bus' import * as Bus from './bus'
import { ShadowPortal } from './components/ShadowPortal' import { ShadowPortal } from './components/ShadowPortal'
import { Errors, SupportedErrorEvent } from './container/Errors' import { Errors, SupportedErrorEvent } from './container/Errors'
import { BuildError } from './container/BuildError'
import { ErrorBoundary } from './ErrorBoundary' import { ErrorBoundary } from './ErrorBoundary'
import { Base } from './styles/Base' import { Base } from './styles/Base'
import { ComponentStyles } from './styles/ComponentStyles' import { ComponentStyles } from './styles/ComponentStyles'
...@@ -9,11 +10,21 @@ import { CssReset } from './styles/CssReset' ...@@ -9,11 +10,21 @@ import { CssReset } from './styles/CssReset'
type OverlayState = { type OverlayState = {
nextId: number nextId: number
buildError: string | null
errors: SupportedErrorEvent[] errors: SupportedErrorEvent[]
} }
function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
switch (ev.type) { 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_ERROR:
case Bus.TYPE_UNHANDLED_REJECTION: { case Bus.TYPE_UNHANDLED_REJECTION: {
return { return {
...@@ -22,9 +33,6 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { ...@@ -22,9 +33,6 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
errors: [...state.errors, { id: state.nextId, event: ev }], errors: [...state.errors, { id: state.nextId, event: ev }],
} }
} }
case Bus.TYPE_REFFRESH: {
return { ...state, errors: [] }
}
default: { default: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
const _: never = ev const _: never = ev
...@@ -36,7 +44,7 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState { ...@@ -36,7 +44,7 @@ function reducer(state: OverlayState, ev: Bus.BusEvent): OverlayState {
function ReactDevOverlay({ children }) { function ReactDevOverlay({ children }) {
const [state, dispatch] = React.useReducer< const [state, dispatch] = React.useReducer<
React.Reducer<OverlayState, Bus.BusEvent> React.Reducer<OverlayState, Bus.BusEvent>
>(reducer, { nextId: 1, errors: [] }) >(reducer, { nextId: 1, buildError: null, errors: [] })
React.useEffect(() => { React.useEffect(() => {
Bus.on(dispatch) Bus.on(dispatch)
...@@ -52,18 +60,28 @@ function ReactDevOverlay({ children }) { ...@@ -52,18 +60,28 @@ function ReactDevOverlay({ children }) {
[] []
) )
const hasBuildError = state.buildError != null
const hasRuntimeErrors = Boolean(state.errors.length)
const isMounted = hasBuildError || hasRuntimeErrors
return ( return (
<React.Fragment> <React.Fragment>
<ErrorBoundary onError={onComponentError}> <ErrorBoundary onError={onComponentError}>
{children ?? null} {children ?? null}
</ErrorBoundary> </ErrorBoundary>
{state.errors.length ? ( {isMounted ? (
<ShadowPortal> <ShadowPortal>
<CssReset /> <CssReset />
<Base /> <Base />
<ComponentStyles /> <ComponentStyles />
<Errors errors={state.errors} /> {hasBuildError ? (
<BuildError message={state.buildError} />
) : hasRuntimeErrors ? (
<Errors errors={state.errors} />
) : (
undefined
)}
</ShadowPortal> </ShadowPortal>
) : ( ) : (
undefined undefined
......
import { StackFrame } from 'stacktrace-parser' 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_REFFRESH = 'fast-refresh'
export const TYPE_UNHANDLED_ERROR = 'unhandled-error' export const TYPE_UNHANDLED_ERROR = 'unhandled-error'
export const TYPE_UNHANDLED_REJECTION = 'unhandled-rejection' 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 FastRefresh = { type: typeof TYPE_REFFRESH }
export type UnhandledError = { export type UnhandledError = {
type: typeof TYPE_UNHANDLED_ERROR type: typeof TYPE_UNHANDLED_ERROR
...@@ -15,7 +22,13 @@ export type UnhandledRejection = { ...@@ -15,7 +22,13 @@ export type UnhandledRejection = {
reason: Error reason: Error
frames: StackFrame[] frames: StackFrame[]
} }
export type BusEvent = UnhandledError | UnhandledRejection | FastRefresh export type BusEvent =
| BuildOk
| BuildError
| FastRefresh
| UnhandledError
| UnhandledRejection
export type BusEventHandler = (ev: BusEvent) => void export type BusEventHandler = (ev: BusEvent) => void
let handlers: Set<BusEventHandler> = new Set() let handlers: Set<BusEventHandler> = new Set()
......
...@@ -3,11 +3,12 @@ import allyTrap from 'ally.js/maintain/tab-focus' ...@@ -3,11 +3,12 @@ import allyTrap from 'ally.js/maintain/tab-focus'
import * as React from 'react' import * as React from 'react'
import { lock, unlock } from './body-locker' 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({ const Overlay: React.FC<OverlayProps> = function Overlay({
className, className,
children, children,
fixed,
}) { }) {
React.useEffect(() => { React.useEffect(() => {
lock() lock()
...@@ -36,7 +37,10 @@ const Overlay: React.FC<OverlayProps> = function Overlay({ ...@@ -36,7 +37,10 @@ const Overlay: React.FC<OverlayProps> = function Overlay({
return ( return (
<div data-nextjs-dialog-overlay className={className} ref={onOverlay}> <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} {children}
</div> </div>
) )
......
...@@ -27,6 +27,12 @@ const styles = css` ...@@ -27,6 +27,12 @@ const styles = css`
pointer-events: all; pointer-events: all;
z-index: -1; z-index: -1;
} }
[data-nextjs-dialog-backdrop-fixed] {
cursor: not-allowed;
-webkit-backdrop-filter: blur(8px);
backdrop-filter: blur(8px);
}
` `
export { styles } 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' ...@@ -3,7 +3,9 @@ import { styles as codeFrame } from '../components/CodeFrame/styles'
import { styles as dialog } from '../components/Dialog' import { styles as dialog } from '../components/Dialog'
import { styles as leftRightDialogHeader } from '../components/LeftRightDialogHeader/styles' import { styles as leftRightDialogHeader } from '../components/LeftRightDialogHeader/styles'
import { styles as overlay } from '../components/Overlay/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 toast } from '../components/Toast'
import { styles as buildErrorStyles } from '../container/BuildError'
import { styles as containerErrorStyles } from '../container/Errors' import { styles as containerErrorStyles } from '../container/Errors'
import { styles as containerRuntimeErrorStyles } from '../container/RuntimeError' import { styles as containerRuntimeErrorStyles } from '../container/RuntimeError'
import { noop as css } from '../helpers/noop-template' import { noop as css } from '../helpers/noop-template'
...@@ -18,7 +20,9 @@ export function ComponentStyles() { ...@@ -18,7 +20,9 @@ export function ComponentStyles() {
${dialog} ${dialog}
${leftRightDialogHeader} ${leftRightDialogHeader}
${codeFrame} ${codeFrame}
${terminal}
${buildErrorStyles}
${containerErrorStyles} ${containerErrorStyles}
${containerRuntimeErrorStyles} ${containerRuntimeErrorStyles}
`, `,
......
...@@ -86,7 +86,9 @@ test('can recover from a syntax error without losing state', async () => { ...@@ -86,7 +86,9 @@ test('can recover from a syntax error without losing state', async () => {
).toBe('1') ).toBe('1')
await session.patch('index.js', `export default () => <div/`) 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( await session.patch(
'index.js', 'index.js',
......
...@@ -106,16 +106,6 @@ export async function sandbox(id = nanoid()) { ...@@ -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) { async hasRedbox(expected = false) {
let attempts = 3 let attempts = 3
do { do {
...@@ -124,7 +114,9 @@ export async function sandbox(id = nanoid()) { ...@@ -124,7 +114,9 @@ export async function sandbox(id = nanoid()) {
[].slice [].slice
.call(document.querySelectorAll('nextjs-portal')) .call(document.querySelectorAll('nextjs-portal'))
.find(p => .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()) { ...@@ -144,10 +136,14 @@ export async function sandbox(id = nanoid()) {
const portal = [].slice const portal = [].slice
.call(document.querySelectorAll('nextjs-portal')) .call(document.querySelectorAll('nextjs-portal'))
.find(p => .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 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