Unverified Commit 3e22b22a authored by Tobias Koppers's avatar Tobias Koppers Committed by GitHub

Hmr DX improvements (#29753)

parent 597fc331
...@@ -13,6 +13,7 @@ let previousClient: import('webpack').Compiler | null = null ...@@ -13,6 +13,7 @@ let previousClient: import('webpack').Compiler | null = null
let previousServer: import('webpack').Compiler | null = null let previousServer: import('webpack').Compiler | null = null
type CompilerDiagnostics = { type CompilerDiagnostics = {
modules: number
errors: string[] | null errors: string[] | null
warnings: string[] | null warnings: string[] | null
} }
...@@ -36,31 +37,10 @@ export type AmpPageStatus = { ...@@ -36,31 +37,10 @@ export type AmpPageStatus = {
type BuildStatusStore = { type BuildStatusStore = {
client: WebpackStatus client: WebpackStatus
server: WebpackStatus server: WebpackStatus
trigger: string | undefined
amp: AmpPageStatus amp: AmpPageStatus
} }
// eslint typescript has a bug with TS enums
/* eslint-disable no-shadow */
enum WebpackStatusPhase {
COMPILING = 1,
COMPILED_WITH_ERRORS = 2,
COMPILED_WITH_WARNINGS = 4,
COMPILED = 5,
}
function getWebpackStatusPhase(status: WebpackStatus): WebpackStatusPhase {
if (status.loading) {
return WebpackStatusPhase.COMPILING
}
if (status.errors) {
return WebpackStatusPhase.COMPILED_WITH_ERRORS
}
if (status.warnings) {
return WebpackStatusPhase.COMPILED_WITH_WARNINGS
}
return WebpackStatusPhase.COMPILED
}
export function formatAmpMessages(amp: AmpPageStatus) { export function formatAmpMessages(amp: AmpPageStatus) {
let output = chalk.bold('Amp Validation') + '\n\n' let output = chalk.bold('Amp Validation') + '\n\n'
let messages: string[][] = [] let messages: string[][] = []
...@@ -118,45 +98,66 @@ export function formatAmpMessages(amp: AmpPageStatus) { ...@@ -118,45 +98,66 @@ export function formatAmpMessages(amp: AmpPageStatus) {
const buildStore = createStore<BuildStatusStore>() const buildStore = createStore<BuildStatusStore>()
buildStore.subscribe((state) => { buildStore.subscribe((state) => {
const { amp, client, server } = state const { amp, client, server, trigger } = state
const [{ status }] = [
{ status: client, phase: getWebpackStatusPhase(client) },
{ status: server, phase: getWebpackStatusPhase(server) },
].sort((a, b) => a.phase.valueOf() - b.phase.valueOf())
const { bootstrap: bootstrapping, appUrl } = consoleStore.getState() const { bootstrap: bootstrapping, appUrl } = consoleStore.getState()
if (bootstrapping && status.loading) { if (bootstrapping && (client.loading || server.loading)) {
return return
} }
let partialState: Partial<OutputState> = { if (client.loading || server.loading) {
consoleStore.setState(
{
bootstrap: false, bootstrap: false,
appUrl: appUrl!, appUrl: appUrl!,
loading: true,
trigger,
} as OutputState,
true
)
return
} }
if (status.loading) { let partialState: Partial<OutputState> = {
bootstrap: false,
appUrl: appUrl!,
loading: false,
typeChecking: false,
modules: client.modules + server.modules,
}
if (client.errors) {
// Show only client errors
consoleStore.setState( consoleStore.setState(
{ ...partialState, loading: true } as OutputState, {
...partialState,
errors: client.errors,
warnings: null,
} as OutputState,
true
)
} else if (server.errors) {
// Show only server errors
consoleStore.setState(
{
...partialState,
errors: server.errors,
warnings: null,
} as OutputState,
true true
) )
} else { } else {
let { errors, warnings } = status // Show warnings from all of them
const warnings = [
if (errors == null) { ...(client.warnings || []),
if (Object.keys(amp).length > 0) { ...(server.warnings || []),
warnings = (warnings || []).concat(formatAmpMessages(amp) || []) ...((Object.keys(amp).length > 0 && formatAmpMessages(amp)) || []),
if (!warnings.length) warnings = null ]
}
}
consoleStore.setState( consoleStore.setState(
{ {
...partialState, ...partialState,
loading: false, errors: null,
typeChecking: false, warnings: warnings.length === 0 ? null : warnings,
errors,
warnings,
} as OutputState, } as OutputState,
true true
) )
...@@ -200,6 +201,7 @@ export function watchCompilers( ...@@ -200,6 +201,7 @@ export function watchCompilers(
buildStore.setState({ buildStore.setState({
client: { loading: true }, client: { loading: true },
server: { loading: true }, server: { loading: true },
trigger: 'initial',
}) })
function tapCompiler( function tapCompiler(
...@@ -213,7 +215,7 @@ export function watchCompilers( ...@@ -213,7 +215,7 @@ export function watchCompilers(
compiler.hooks.done.tap( compiler.hooks.done.tap(
`NextJsDone-${key}`, `NextJsDone-${key}`,
(stats: import('webpack').Stats) => { (stats: import('webpack5').Stats) => {
buildStore.setState({ amp: {} }) buildStore.setState({ amp: {} })
const { errors, warnings } = formatWebpackMessages( const { errors, warnings } = formatWebpackMessages(
...@@ -225,6 +227,7 @@ export function watchCompilers( ...@@ -225,6 +227,7 @@ export function watchCompilers(
onEvent({ onEvent({
loading: false, loading: false,
modules: stats.compilation.modules.size,
errors: hasErrors ? errors : null, errors: hasErrors ? errors : null,
warnings: hasWarnings ? warnings : null, warnings: hasWarnings ? warnings : null,
}) })
...@@ -232,13 +235,37 @@ export function watchCompilers( ...@@ -232,13 +235,37 @@ export function watchCompilers(
) )
} }
tapCompiler('client', client, (status) => tapCompiler('client', client, (status) => {
buildStore.setState({ client: status }) if (!status.loading && !buildStore.getState().server.loading) {
) buildStore.setState({
tapCompiler('server', server, (status) => client: status,
buildStore.setState({ server: status }) trigger: undefined,
) })
} else {
buildStore.setState({
client: status,
})
}
})
tapCompiler('server', server, (status) => {
if (!status.loading && !buildStore.getState().client.loading) {
buildStore.setState({
server: status,
trigger: undefined,
})
} else {
buildStore.setState({
server: status,
})
}
})
previousClient = client previousClient = client
previousServer = server previousServer = server
} }
export function reportTrigger(trigger: string) {
buildStore.setState({
trigger,
})
}
...@@ -7,10 +7,14 @@ import * as Log from './log' ...@@ -7,10 +7,14 @@ import * as Log from './log'
export type OutputState = export type OutputState =
| { bootstrap: true; appUrl: string | null; bindAddr: string | null } | { bootstrap: true; appUrl: string | null; bindAddr: string | null }
| ({ bootstrap: false; appUrl: string | null; bindAddr: string | null } & ( | ({ bootstrap: false; appUrl: string | null; bindAddr: string | null } & (
| { loading: true } | {
loading: true
trigger: string | undefined
}
| { | {
loading: false loading: false
typeChecking: boolean typeChecking: boolean
modules: number
errors: string[] | null errors: string[] | null
warnings: string[] | null warnings: string[] | null
} }
...@@ -49,11 +53,16 @@ store.subscribe((state) => { ...@@ -49,11 +53,16 @@ store.subscribe((state) => {
if (state.appUrl) { if (state.appUrl) {
Log.ready(`started server on ${state.bindAddr}, url: ${state.appUrl}`) Log.ready(`started server on ${state.bindAddr}, url: ${state.appUrl}`)
} }
if (startTime === 0) startTime = Date.now()
return return
} }
if (state.loading) { if (state.loading) {
if (state.trigger) {
Log.wait(`compiling ${state.trigger}...`)
} else {
Log.wait('compiling...') Log.wait('compiling...')
}
if (startTime === 0) startTime = Date.now() if (startTime === 0) startTime = Date.now()
return return
} }
...@@ -89,6 +98,11 @@ store.subscribe((state) => { ...@@ -89,6 +98,11 @@ store.subscribe((state) => {
time > 2000 ? ` in ${Math.round(time / 100) / 10} s` : ` in ${time} ms` time > 2000 ? ` in ${Math.round(time / 100) / 10} s` : ` in ${time} ms`
} }
let modulesMessage = ''
if (state.modules) {
modulesMessage = ` (${state.modules} modules)`
}
if (state.warnings) { if (state.warnings) {
Log.warn(state.warnings.join('\n\n')) Log.warn(state.warnings.join('\n\n'))
// Ensure traces are flushed after each compile in development mode // Ensure traces are flushed after each compile in development mode
...@@ -98,12 +112,12 @@ store.subscribe((state) => { ...@@ -98,12 +112,12 @@ store.subscribe((state) => {
if (state.typeChecking) { if (state.typeChecking) {
Log.info( Log.info(
`bundled successfully${timeMessage}, waiting for typecheck results...` `bundled successfully${timeMessage}${modulesMessage}, waiting for typecheck results...`
) )
return return
} }
Log.event(`compiled successfully${timeMessage}`) Log.event(`compiled successfully${timeMessage}${modulesMessage}`)
// Ensure traces are flushed after each compile in development mode // Ensure traces are flushed after each compile in development mode
flushAllTraces() flushAllTraces()
}) })
...@@ -3,12 +3,12 @@ import { IncomingMessage, ServerResponse } from 'http' ...@@ -3,12 +3,12 @@ import { IncomingMessage, ServerResponse } from 'http'
import { join, posix } from 'path' import { join, posix } from 'path'
import { parse } from 'url' import { parse } from 'url'
import { webpack } from 'next/dist/compiled/webpack/webpack' import { webpack } from 'next/dist/compiled/webpack/webpack'
import * as Log from '../../build/output/log'
import { normalizePagePath, normalizePathSep } from '../normalize-page-path' import { normalizePagePath, normalizePathSep } from '../normalize-page-path'
import { pageNotFoundError } from '../require' import { pageNotFoundError } from '../require'
import { findPageFile } from '../lib/find-page-file' import { findPageFile } from '../lib/find-page-file'
import getRouteFromEntrypoint from '../get-route-from-entrypoint' import getRouteFromEntrypoint from '../get-route-from-entrypoint'
import { API_ROUTE } from '../../lib/constants' import { API_ROUTE } from '../../lib/constants'
import { reportTrigger } from '../../build/output'
export const ADDED = Symbol('added') export const ADDED = Symbol('added')
export const BUILDING = Symbol('building') export const BUILDING = Symbol('building')
...@@ -228,12 +228,12 @@ export default function onDemandEntryHandler( ...@@ -228,12 +228,12 @@ export default function onDemandEntryHandler(
: Promise.all([addPageEntry('client'), addPageEntry('server')]) : Promise.all([addPageEntry('client'), addPageEntry('server')])
if (entriesChanged) { if (entriesChanged) {
Log.event( reportTrigger(
isApiRoute isApiRoute
? `build page: ${normalizedPage} (server only)` ? `${normalizedPage} (server only)`
: clientOnly : clientOnly
? `build page: ${normalizedPage} (client only)` ? `${normalizedPage} (client only)`
: `build page: ${normalizedPage}` : normalizedPage
) )
invalidator.invalidate() invalidator.invalidate()
} }
......
...@@ -520,7 +520,7 @@ describe('AMP Usage', () => { ...@@ -520,7 +520,7 @@ describe('AMP Usage', () => {
it('should not contain missing files warning', async () => { it('should not contain missing files warning', async () => {
expect(output).toContain('compiled successfully') expect(output).toContain('compiled successfully')
expect(output).toContain('build page: /only-amp') expect(output).toContain('compiling /only-amp')
expect(output).not.toContain('Could not find files for') expect(output).not.toContain('Could not find files for')
}) })
}) })
......
...@@ -31,6 +31,7 @@ describe('GS(S)P Server-Side Change Reloading', () => { ...@@ -31,6 +31,7 @@ describe('GS(S)P Server-Side Change Reloading', () => {
it('should not reload page when client-side is changed too GSP', async () => { it('should not reload page when client-side is changed too GSP', async () => {
const browser = await webdriver(appPort, '/gsp-blog/first') const browser = await webdriver(appPort, '/gsp-blog/first')
await check(() => browser.elementByCss('#change').text(), 'change me')
await browser.eval(() => (window.beforeChange = 'hi')) await browser.eval(() => (window.beforeChange = 'hi'))
const props = JSON.parse(await browser.elementByCss('#props').text()) const props = JSON.parse(await browser.elementByCss('#props').text())
...@@ -145,6 +146,7 @@ describe('GS(S)P Server-Side Change Reloading', () => { ...@@ -145,6 +146,7 @@ describe('GS(S)P Server-Side Change Reloading', () => {
it('should not reload page when client-side is changed too GSSP', async () => { it('should not reload page when client-side is changed too GSSP', async () => {
const browser = await webdriver(appPort, '/gssp-blog/first') const browser = await webdriver(appPort, '/gssp-blog/first')
await check(() => browser.elementByCss('#change').text(), 'change me')
await browser.eval(() => (window.beforeChange = 'hi')) await browser.eval(() => (window.beforeChange = 'hi'))
const props = JSON.parse(await browser.elementByCss('#props').text()) const props = JSON.parse(await browser.elementByCss('#props').text())
...@@ -165,6 +167,11 @@ describe('GS(S)P Server-Side Change Reloading', () => { ...@@ -165,6 +167,11 @@ describe('GS(S)P Server-Side Change Reloading', () => {
it('should update page when getServerSideProps is changed only', async () => { it('should update page when getServerSideProps is changed only', async () => {
const browser = await webdriver(appPort, '/gssp-blog/first') const browser = await webdriver(appPort, '/gssp-blog/first')
await check(
async () =>
JSON.parse(await browser.elementByCss('#props').text()).count + '',
'1'
)
await browser.eval(() => (window.beforeChange = 'hi')) await browser.eval(() => (window.beforeChange = 'hi'))
const props = JSON.parse(await browser.elementByCss('#props').text()) const props = JSON.parse(await browser.elementByCss('#props').text())
......
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