Unverified Commit 09e38847 authored by Joe Haddad's avatar Joe Haddad Committed by GitHub

Update HMR Client Runtime (#11977)

* Update HMR Client Runtime

* Increment event when building or different state

* Dismiss Old Type-Only Overlay

* Update packages/next/client/dev/error-overlay/hot-dev-client.js
parent 48e2c19d
/* eslint-disable camelcase */
/** /**
MIT License * MIT License
*
Copyright (c) 2013-present, Facebook, Inc. * Copyright (c) 2013-present, Facebook, Inc.
*
Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
*
The above copyright notice and this permission notice shall be included in all * The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software. * copies or substantial portions of the Software.
*
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. * SOFTWARE.
*/ */
// This file is based on https://github.com/facebook/create-react-app/blob/v1.1.4/packages/react-dev-utils/webpackHotDevClient.js
// It's been edited to rely on webpack-hot-middleware and to be more compatible with SSR / Next.js // This file is a modified version of the Create React App HMR dev client that
// can be found here:
// https://github.com/facebook/create-react-app/blob/v3.4.1/packages/react-dev-utils/webpackHotDevClient.js
import { getEventSourceWrapper } from './eventsource' import { getEventSourceWrapper } from './eventsource'
import formatWebpackMessages from './format-webpack-messages' import formatWebpackMessages from './format-webpack-messages'
...@@ -41,10 +42,6 @@ import fetch from 'next/dist/build/polyfills/unfetch' ...@@ -41,10 +42,6 @@ import fetch from 'next/dist/build/polyfills/unfetch'
// that looks similar to our console output. The error overlay is inspired by: // that looks similar to our console output. The error overlay is inspired by:
// https://github.com/glenjamin/webpack-hot-middleware // https://github.com/glenjamin/webpack-hot-middleware
// This is a modified version of create-react-app's webpackHotDevClient.js
// It implements webpack-hot-middleware's EventSource events instead of webpack-dev-server's websocket.
// https://github.com/facebook/create-react-app/blob/25184c4e91ebabd16fe1cde3d8630830e4a36a01/packages/react-dev-utils/webpackHotDevClient.js
let hadRuntimeError = false let hadRuntimeError = false
let customHmrEventHandler let customHmrEventHandler
export default function connect(options) { export default function connect(options) {
...@@ -121,7 +118,7 @@ export default function connect(options) { ...@@ -121,7 +118,7 @@ export default function connect(options) {
var isFirstCompilation = true var isFirstCompilation = true
var mostRecentCompilationHash = null var mostRecentCompilationHash = null
var hasCompileErrors = false var hasCompileErrors = false
let deferredBuildError = null var hmrEventCount = 0
function clearOutdatedErrors() { function clearOutdatedErrors() {
// Clean up outdated compile errors, if any. // Clean up outdated compile errors, if any.
...@@ -130,12 +127,12 @@ function clearOutdatedErrors() { ...@@ -130,12 +127,12 @@ function clearOutdatedErrors() {
console.clear() console.clear()
} }
} }
deferredBuildError = null
} }
// Successful compilation. // Successful compilation.
function handleSuccess() { function handleSuccess() {
clearOutdatedErrors()
const isHotUpdate = !isFirstCompilation const isHotUpdate = !isFirstCompilation
isFirstCompilation = false isFirstCompilation = false
hasCompileErrors = false hasCompileErrors = false
...@@ -143,13 +140,9 @@ function handleSuccess() { ...@@ -143,13 +140,9 @@ function handleSuccess() {
// Attempt to apply hot updates or reload. // Attempt to apply hot updates or reload.
if (isHotUpdate) { if (isHotUpdate) {
tryApplyUpdates(function onHotUpdateSuccess() { tryApplyUpdates(function onHotUpdateSuccess() {
if (deferredBuildError) { // Only dismiss it when we're sure it's a hot update.
deferredBuildError() // Otherwise it would flicker right before the reload.
} else { tryDismissErrorOverlay()
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
ErrorOverlay.dismissBuildError()
}
}) })
} }
} }
...@@ -158,24 +151,41 @@ function handleSuccess() { ...@@ -158,24 +151,41 @@ function handleSuccess() {
function handleWarnings(warnings) { function handleWarnings(warnings) {
clearOutdatedErrors() clearOutdatedErrors()
// Print warnings to the console. const isHotUpdate = !isFirstCompilation
const formatted = formatWebpackMessages({ isFirstCompilation = false
warnings: warnings, hasCompileErrors = false
errors: [],
})
if (typeof console !== 'undefined' && typeof console.warn === 'function') { function printWarnings() {
for (let i = 0; i < formatted.warnings.length; i++) { // Print warnings to the console.
if (i === 5) { const formatted = formatWebpackMessages({
console.warn( warnings: warnings,
'There were more warnings in other files.\n' + errors: [],
'You can find a complete log in the terminal.' })
)
break if (typeof console !== 'undefined' && typeof console.warn === 'function') {
for (let i = 0; i < formatted.warnings.length; i++) {
if (i === 5) {
console.warn(
'There were more warnings in other files.\n' +
'You can find a complete log in the terminal.'
)
break
}
console.warn(stripAnsi(formatted.warnings[i]))
} }
console.warn(stripAnsi(formatted.warnings[i]))
} }
} }
printWarnings()
// Attempt to apply hot updates or reload.
if (isHotUpdate) {
tryApplyUpdates(function onSuccessfulHotUpdate() {
// Only dismiss it when we're sure it's a hot update.
// Otherwise it would flicker right before the reload.
tryDismissErrorOverlay()
})
}
} }
// Compilation with errors (e.g. syntax error or missing modules). // Compilation with errors (e.g. syntax error or missing modules).
...@@ -200,6 +210,15 @@ function handleErrors(errors) { ...@@ -200,6 +210,15 @@ function handleErrors(errors) {
console.error(stripAnsi(formatted.errors[i])) console.error(stripAnsi(formatted.errors[i]))
} }
} }
// Do not attempt to reload now.
// We will reload on next success instead.
}
function tryDismissErrorOverlay() {
if (!hasCompileErrors) {
ErrorOverlay.dismissBuildError()
}
} }
// There is a newer version of the code available. // There is a newer version of the code available.
...@@ -213,6 +232,7 @@ function processMessage(e) { ...@@ -213,6 +232,7 @@ function processMessage(e) {
const obj = JSON.parse(e.data) const obj = JSON.parse(e.data)
switch (obj.action) { switch (obj.action) {
case 'building': { case 'building': {
++hmrEventCount
console.log( console.log(
'[HMR] bundle ' + (obj.name ? "'" + obj.name + "' " : '') + 'rebuilding' '[HMR] bundle ' + (obj.name ? "'" + obj.name + "' " : '') + 'rebuilding'
) )
...@@ -220,46 +240,58 @@ function processMessage(e) { ...@@ -220,46 +240,58 @@ function processMessage(e) {
} }
case 'built': case 'built':
case 'sync': { case 'sync': {
clearOutdatedErrors() if (obj.action === 'built') ++hmrEventCount
if (obj.hash) { if (obj.hash) {
handleAvailableHash(obj.hash) handleAvailableHash(obj.hash)
} }
const { errors, warnings } = obj const { errors, warnings } = obj
const hasErrors = Boolean(errors && errors.length) const hasErrors = Boolean(errors && errors.length)
const hasWarnings = Boolean(warnings && warnings.length)
if (hasErrors) { if (hasErrors) {
// When there is a compilation error coming from SSR we have to reload the page on next successful compile return handleErrors(errors)
if (obj.action === 'sync') { }
hadRuntimeError = true
}
handleErrors(errors) const hasWarnings = Boolean(warnings && warnings.length)
break if (hasWarnings) {
} else if (hasWarnings) { return handleWarnings(warnings)
handleWarnings(warnings)
} }
handleSuccess() return handleSuccess()
break
} }
case 'typeChecked': { case 'typeChecked': {
const [{ errors, warnings }] = obj.data const eventId = ++hmrEventCount
const [{ errors }] = obj.data
const hasErrors = Boolean(errors && errors.length) const hasErrors = Boolean(errors && errors.length)
const hasWarnings = Boolean(warnings && warnings.length) // Disregard event if there are no errors to report.
if (!hasErrors) {
// We need to _try_ dismissing the error overlay, as code may not have
// changed, for example, when only types are updated.
// n.b. `handleSuccess` only dismisses the overlay if code was updated.
tryDismissErrorOverlay()
break
}
if (hasErrors) { function display() {
if (canApplyUpdates()) { // Another update has started, ignore type update:
handleErrors(errors) if (!canApplyUpdates() || eventId !== hmrEventCount) {
} else { return
deferredBuildError = () => handleErrors(errors) }
// TypeScript errors to not take priority over compillation errors
if (hasCompileErrors) {
return
} }
} else if (hasWarnings) {
handleWarnings(warnings) handleErrors(errors)
}
// We need to defer this until we're in an idle state.
if (canApplyUpdates()) {
display()
} else {
afterApplyUpdates(display)
} }
break break
...@@ -286,9 +318,22 @@ function isUpdateAvailable() { ...@@ -286,9 +318,22 @@ function isUpdateAvailable() {
function canApplyUpdates() { function canApplyUpdates() {
return module.hot.status() === 'idle' return module.hot.status() === 'idle'
} }
function afterApplyUpdates(fn) {
if (canApplyUpdates()) {
fn()
} else {
function handler(status) {
if (status === 'idle') {
module.hot.removeStatusHandler(handler)
fn()
}
}
module.hot.addStatusHandler(handler)
}
}
// Attempt to update code on the fly, fall back to a hard reload. // Attempt to update code on the fly, fall back to a hard reload.
async function tryApplyUpdates(onHotUpdateSuccess) { function tryApplyUpdates(onHotUpdateSuccess) {
if (!module.hot) { if (!module.hot) {
// HotModuleReplacementPlugin is not in Webpack configuration. // HotModuleReplacementPlugin is not in Webpack configuration.
console.error('HotModuleReplacementPlugin is not in Webpack configuration.') console.error('HotModuleReplacementPlugin is not in Webpack configuration.')
...@@ -297,12 +342,11 @@ async function tryApplyUpdates(onHotUpdateSuccess) { ...@@ -297,12 +342,11 @@ async function tryApplyUpdates(onHotUpdateSuccess) {
} }
if (!isUpdateAvailable() || !canApplyUpdates()) { if (!isUpdateAvailable() || !canApplyUpdates()) {
ErrorOverlay.dismissBuildError()
return return
} }
function handleApplyUpdates(err, updatedModules) { function handleApplyUpdates(err, updatedModules) {
if (err || hadRuntimeError) { if (err || hadRuntimeError || !updatedModules) {
if (err) { if (err) {
console.warn('Error while applying updates, reloading page', err) console.warn('Error while applying updates, reloading page', err)
} }
...@@ -324,17 +368,13 @@ async function tryApplyUpdates(onHotUpdateSuccess) { ...@@ -324,17 +368,13 @@ async function tryApplyUpdates(onHotUpdateSuccess) {
} }
} }
// https://webpack.github.io/docs/hot-module-replacement.html#check // https://webpack.js.org/api/hot-module-replacement/#check
try { module.hot.check(/* autoApply */ true).then(
const updatedModules = await module.hot.check( updatedModules => {
/* autoApply */ {
ignoreUnaccepted: true,
}
)
if (updatedModules) {
handleApplyUpdates(null, updatedModules) handleApplyUpdates(null, updatedModules)
},
err => {
handleApplyUpdates(err, null)
} }
} catch (err) { )
handleApplyUpdates(err, null)
}
} }
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