Implement hot-reloader interface (#54629)

Splits out the public API that is used for the hot reloader. This will
be used in a follow-up PR to implement the same interface for Turbopack.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->
This commit is contained in:
Tim Neutkens 2023-08-27 23:12:36 +02:00 committed by GitHub
parent 27020e299e
commit 6ea0763224
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 55 additions and 10 deletions

View file

@ -0,0 +1,44 @@
import type { IncomingMessage, ServerResponse } from 'http'
import type { UrlObject } from 'url'
import type { Duplex } from 'stream'
import type { webpack } from 'next/dist/compiled/webpack/webpack'
import type getBaseWebpackConfig from '../../build/webpack-config'
import type { RouteMatch } from '../future/route-matches/route-match'
export interface NextJsHotReloaderInterface {
activeConfigs?: Array<Awaited<ReturnType<typeof getBaseWebpackConfig>>>
serverStats: webpack.Stats | null
edgeServerStats: webpack.Stats | null
run(
req: IncomingMessage,
res: ServerResponse,
parsedUrl: UrlObject
): Promise<{ finished?: true }>
setHmrServerError(error: Error | null): void
clearHmrServerError(): void
start(): Promise<void>
stop(): Promise<void>
send(action?: string | any, ...args: any[]): void
getCompilationErrors(page: string): Promise<any[]>
onHMR(req: IncomingMessage, _socket: Duplex, head: Buffer): void
invalidate({
reloadAfterInvalidation,
}: {
reloadAfterInvalidation: boolean
}): void
buildFallbackError(): Promise<void>
ensurePage({
page,
clientOnly,
appPaths,
match,
isApp,
}: {
page: string
clientOnly: boolean
appPaths?: string[] | null
isApp?: boolean
match?: RouteMatch
}): Promise<void>
}

View file

@ -2,13 +2,13 @@ import type { NextConfigComplete } from '../config-shared'
import type { CustomRoutes } from '../../lib/load-custom-routes' import type { CustomRoutes } from '../../lib/load-custom-routes'
import type { Duplex } from 'stream' import type { Duplex } from 'stream'
import type { Telemetry } from '../../telemetry/storage' import type { Telemetry } from '../../telemetry/storage'
import type { IncomingMessage, ServerResponse } from 'http'
import type { UrlObject } from 'url'
import { webpack, StringXor } from 'next/dist/compiled/webpack/webpack' import { webpack, StringXor } from 'next/dist/compiled/webpack/webpack'
import { getOverlayMiddleware } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware' import { getOverlayMiddleware } from 'next/dist/compiled/@next/react-dev-overlay/dist/middleware'
import { IncomingMessage, ServerResponse } from 'http'
import { WebpackHotMiddleware } from './hot-middleware' import { WebpackHotMiddleware } from './hot-middleware'
import { join, relative, isAbsolute, posix } from 'path' import { join, relative, isAbsolute, posix } from 'path'
import { UrlObject } from 'url'
import { import {
createEntrypoints, createEntrypoints,
createPagesMapping, createPagesMapping,
@ -67,6 +67,7 @@ import { isAPIRoute } from '../../lib/is-api-route'
import { getRouteLoaderEntry } from '../../build/webpack/loaders/next-route-loader' import { getRouteLoaderEntry } from '../../build/webpack/loaders/next-route-loader'
import { isInternalComponent } from '../../lib/is-internal-component' import { isInternalComponent } from '../../lib/is-internal-component'
import { RouteKind } from '../future/route-kind' import { RouteKind } from '../future/route-kind'
import { NextJsHotReloaderInterface } from './hot-reloader-types'
const MILLISECONDS_IN_NANOSECOND = 1_000_000 const MILLISECONDS_IN_NANOSECOND = 1_000_000
@ -174,7 +175,7 @@ function erroredPages(compilation: webpack.Compilation) {
return failedPages return failedPages
} }
export default class HotReloader { export default class HotReloader implements NextJsHotReloaderInterface {
private hasAmpEntrypoints: boolean private hasAmpEntrypoints: boolean
private hasAppRouterEntrypoints: boolean private hasAppRouterEntrypoints: boolean
private hasPagesRouterEntrypoints: boolean private hasPagesRouterEntrypoints: boolean
@ -185,10 +186,7 @@ export default class HotReloader {
private distDir: string private distDir: string
private webpackHotMiddleware?: WebpackHotMiddleware private webpackHotMiddleware?: WebpackHotMiddleware
private config: NextConfigComplete private config: NextConfigComplete
public hasServerComponents: boolean private clientStats: webpack.Stats | null
public clientStats: webpack.Stats | null
public serverStats: webpack.Stats | null
public edgeServerStats: webpack.Stats | null
private clientError: Error | null = null private clientError: Error | null = null
private serverError: Error | null = null private serverError: Error | null = null
private hmrServerError: Error | null = null private hmrServerError: Error | null = null
@ -209,6 +207,9 @@ export default class HotReloader {
installed: '0.0.0', installed: '0.0.0',
} }
private reloadAfterInvalidation: boolean = false private reloadAfterInvalidation: boolean = false
public serverStats: webpack.Stats | null
public edgeServerStats: webpack.Stats | null
public multiCompiler?: webpack.MultiCompiler public multiCompiler?: webpack.MultiCompiler
public activeConfigs?: Array< public activeConfigs?: Array<
UnwrapPromise<ReturnType<typeof getBaseWebpackConfig>> UnwrapPromise<ReturnType<typeof getBaseWebpackConfig>>
@ -252,7 +253,6 @@ export default class HotReloader {
this.telemetry = telemetry this.telemetry = telemetry
this.config = config this.config = config
this.hasServerComponents = !!this.appDir
this.previewProps = previewProps this.previewProps = previewProps
this.rewrites = rewrites this.rewrites = rewrites
this.hotReloaderSpan = trace('hot-reloader', undefined, { this.hotReloaderSpan = trace('hot-reloader', undefined, {
@ -346,7 +346,7 @@ export default class HotReloader {
} }
} }
public async refreshServerComponents(): Promise<void> { protected async refreshServerComponents(): Promise<void> {
this.send({ this.send({
action: 'serverComponentChanges', action: 'serverComponentChanges',
// TODO: granular reloading of changes // TODO: granular reloading of changes

View file

@ -89,6 +89,7 @@ import { MiddlewareManifest } from '../../../build/webpack/plugins/middleware-pl
import { devPageFiles } from '../../../build/webpack/plugins/next-types-plugin/shared' import { devPageFiles } from '../../../build/webpack/plugins/next-types-plugin/shared'
import type { RenderWorkers } from '../router-server' import type { RenderWorkers } from '../router-server'
import { pathToRegexp } from 'next/dist/compiled/path-to-regexp' import { pathToRegexp } from 'next/dist/compiled/path-to-regexp'
import { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types'
type SetupOpts = { type SetupOpts = {
renderWorkers: RenderWorkers renderWorkers: RenderWorkers
@ -160,7 +161,7 @@ async function startWatcher(opts: SetupOpts) {
>[] >[]
} = {} } = {}
let hotReloader: InstanceType<typeof HotReloader> let hotReloader: NextJsHotReloaderInterface
if (opts.turbo) { if (opts.turbo) {
const { loadBindings } = const { loadBindings } =