Skip to content

Commit

Permalink
Use react dom server node api to detect react root is enabled (#36749)
Browse files Browse the repository at this point in the history
x-ref: #36552 (comment)
x-ref: preactjs/next-plugin-preact#59

`preact/compat` doesn't have `/server.browser` exports, to make it work with latest of next.js: 

* use `react-dom/server` to detect if it could opt-in streaming rendering by checking react 18 `renderToPipeableStream` API in short time fix. In long term `preact/compat`should support `/server.browser` that same with react 17.
* Also filed a PR to `next-plugin-preact` to skip chunk-prepending to pages in edge compiler
  • Loading branch information
huozhi committed May 7, 2022
1 parent 51d962d commit a84672e
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 6 deletions.
3 changes: 1 addition & 2 deletions packages/next/bin/next.ts
Expand Up @@ -43,8 +43,7 @@ const args = arg(
)

// Detect if react-dom is enabled streaming rendering mode
const shouldUseReactRoot = !!require('react-dom/server.browser')
.renderToReadableStream
const shouldUseReactRoot = !!require('react-dom/server').renderToPipeableStream

// Version is inlined into the file using taskr build pipeline
if (args['--version']) {
Expand Down
4 changes: 2 additions & 2 deletions packages/next/server/next.ts
Expand Up @@ -185,8 +185,8 @@ function createServer(options: NextServerOptions): NextServer {

// Make sure env of custom server is overridden.
// Use dynamic require to make sure it's executed in it's own context.
const ReactDOMServer = require('react-dom/server.browser')
const shouldUseReactRoot = !!ReactDOMServer.renderToReadableStream
const ReactDOMServer = require('react-dom/server')
const shouldUseReactRoot = !!ReactDOMServer.renderToPipeableStream
if (shouldUseReactRoot) {
;(process.env as any).__NEXT_REACT_ROOT = 'true'
}
Expand Down
6 changes: 4 additions & 2 deletions packages/next/server/view-render.tsx
Expand Up @@ -17,12 +17,14 @@ import {
continueFromInitialStream,
} from './node-web-streams-helper'
import { FlushEffectsContext } from '../shared/lib/flush-effects'
// @ts-ignore react-dom/client exists when using React 18
import ReactDOMServer from 'react-dom/server.browser'
import { isDynamicRoute } from '../shared/lib/router/utils'
import { tryGetPreviewData } from './api-utils/node'
import DefaultRootLayout from '../lib/views-layout'

const ReactDOMServer = process.env.__NEXT_REACT_ROOT
? require('react-dom/server.browser')
: require('react-dom/server')

export type RenderOptsPartial = {
err?: Error | null
dev?: boolean
Expand Down

0 comments on commit a84672e

Please sign in to comment.