Unverified Commit 6028a7a6 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Remove react root condition and always use concurrent mode (#42141)

Removing the `hasReactRoot` condition and `__NEXT_REACT_ROOT` env var since next 13 requires latest react 18 to be installed, all the react 17 (non concurrent mode) compatible code can be dropped now.
parent 6e734d92
......@@ -95,13 +95,6 @@ if (process.env.NODE_ENV) {
;(process.env as any).NODE_ENV = process.env.NODE_ENV || defaultEnv
;(process.env as any).NEXT_RUNTIME = 'nodejs'
// In node.js runtime, react has to be required after NODE_ENV is set,
// so that the correct dev/prod bundle could be loaded into require.cache.
const { shouldUseReactRoot } = require('../server/utils')
if (shouldUseReactRoot) {
;(process.env as any).__NEXT_REACT_ROOT = 'true'
}
// x-ref: https://github.com/vercel/next.js/pull/34688#issuecomment-1047994505
if (process.versions.pnp === '3') {
const nodeVersionParts = process.versions.node
......
......@@ -274,8 +274,6 @@ export default async function build(
setGlobal('phase', PHASE_PRODUCTION_BUILD)
setGlobal('distDir', distDir)
const hasReactRoot = !!process.env.__NEXT_REACT_ROOT
const { target } = config
const buildId: string = await nextBuildSpan
.traceChild('generate-buildid')
......@@ -910,7 +908,6 @@ export default async function build(
const commonWebpackOptions = {
buildId,
config,
hasReactRoot,
pagesDir,
reactProductionProfiling,
rewrites,
......
import React from 'react'
import ReactRefreshWebpackPlugin from 'next/dist/compiled/@next/react-refresh-utils/dist/ReactRefreshWebpackPlugin'
import chalk from 'next/dist/compiled/chalk'
import crypto from 'crypto'
......@@ -69,6 +70,10 @@ const NEXT_PROJECT_ROOT_DIST_CLIENT = path.join(
'client'
)
if (parseInt(React.version) < 18) {
throw new Error('Next.js requires react >= 18.2.0 to be installed.')
}
const babelIncludeRegexes: RegExp[] = [
/next[\\/]dist[\\/](esm[\\/])?shared[\\/]lib/,
/next[\\/]dist[\\/](esm[\\/])?client/,
......@@ -161,7 +166,6 @@ export function getDefineEnv({
distDir,
isClient,
hasRewrites,
hasReactRoot,
isNodeServer,
isEdgeServer,
middlewareMatchers,
......@@ -170,7 +174,6 @@ export function getDefineEnv({
distDir: string
isClient?: boolean
hasRewrites?: boolean
hasReactRoot?: boolean
isNodeServer?: boolean
isEdgeServer?: boolean
middlewareMatchers?: MiddlewareMatcher[]
......@@ -255,7 +258,6 @@ export function getDefineEnv({
: false
: config.reactStrictMode
),
'process.env.__NEXT_REACT_ROOT': JSON.stringify(hasReactRoot),
'process.env.__NEXT_OPTIMIZE_FONTS': JSON.stringify(
!dev && config.optimizeFonts
),
......@@ -569,7 +571,6 @@ export default async function getBaseWebpackConfig(
compilerType,
dev = false,
entrypoints,
hasReactRoot,
isDevFallback = false,
pagesDir,
reactProductionProfiling = false,
......@@ -584,7 +585,6 @@ export default async function getBaseWebpackConfig(
compilerType: CompilerNameValues
dev?: boolean
entrypoints: webpack.EntryObject
hasReactRoot: boolean
isDevFallback?: boolean
pagesDir?: string
reactProductionProfiling?: boolean
......@@ -608,19 +608,8 @@ export default async function getBaseWebpackConfig(
rewrites.fallback.length > 0
const hasAppDir = !!config.experimental.appDir && !!appDir
const hasConcurrentFeatures = hasReactRoot
const hasServerComponents = hasAppDir
// Only error in first one compiler (client) once
if (isClient) {
if (!hasReactRoot) {
throw new Error('Next.js requires React 18.2.0 to be installed.')
}
}
const disableOptimizedLoading = hasConcurrentFeatures
? true
: config.experimental.disableOptimizedLoading
const disableOptimizedLoading = true
if (isClient) {
if (config.experimental.runtime === SERVER_RUNTIME.edge) {
......@@ -1973,7 +1962,6 @@ export default async function getBaseWebpackConfig(
distDir,
isClient,
hasRewrites,
hasReactRoot,
isNodeServer,
isEdgeServer,
middlewareMatchers,
......@@ -1983,7 +1971,7 @@ export default async function getBaseWebpackConfig(
new ReactLoadablePlugin({
filename: REACT_LOADABLE_MANIFEST,
pagesDir,
runtimeAsset: hasConcurrentFeatures
runtimeAsset: true
? `server/${MIDDLEWARE_REACT_LOADABLE_MANIFEST}.js`
: undefined,
dev,
......@@ -2056,7 +2044,7 @@ export default async function getBaseWebpackConfig(
buildId,
rewrites,
isDevFallback,
exportRuntime: hasConcurrentFeatures,
exportRuntime: true,
appDirEnabled: hasAppDir,
}),
new ProfilingPlugin({ runWebpackSpan }),
......
......@@ -794,19 +794,13 @@ export default function Image({
}
}
let imageSrcSetPropName = 'imagesrcset'
let imageSizesPropName = 'imagesizes'
if (process.env.__NEXT_REACT_ROOT) {
imageSrcSetPropName = 'imageSrcSet'
imageSizesPropName = 'imageSizes'
}
const linkProps: React.DetailedHTMLProps<
React.LinkHTMLAttributes<HTMLLinkElement>,
HTMLLinkElement
> = {
// Note: imagesrcset and imagesizes are not in the link element type with react 17.
[imageSrcSetPropName]: imgAttributes.srcSet,
[imageSizesPropName]: imgAttributes.sizes,
// @ts-expect-error upgrade react types to react 18
imageSrcSet: imgAttributes.srcSet,
imageSizes: imgAttributes.sizes,
crossOrigin: rest.crossOrigin,
}
......
/* global location */
import '../build/polyfills/polyfill-module'
import type Router from '../shared/lib/router/router'
import React from 'react'
// @ts-expect-error upgrade react types to react 18
import ReactDOM from 'react-dom/client'
import { HeadManagerContext } from '../shared/lib/head-manager-context'
import mitt, { MittEmitter } from '../shared/lib/mitt'
import { RouterContext } from '../shared/lib/router-context'
import type Router from '../shared/lib/router/router'
import {
AppComponent,
AppProps,
......@@ -35,10 +37,6 @@ import { ImageConfigComplete } from '../shared/lib/image-config'
import { removeBasePath } from './remove-base-path'
import { hasBasePath } from './has-base-path'
const ReactDOM = process.env.__NEXT_REACT_ROOT
? require('react-dom/client')
: require('react-dom')
/// <reference types="react-dom/experimental" />
declare let __webpack_public_path__: string
......@@ -492,26 +490,16 @@ function renderReactElement(
}
const reactEl = fn(shouldHydrate ? markHydrateComplete : markRenderComplete)
if (process.env.__NEXT_REACT_ROOT) {
if (!reactRoot) {
// Unlike with createRoot, you don't need a separate root.render() call here
reactRoot = ReactDOM.hydrateRoot(domEl, reactEl)
// TODO: Remove shouldHydrate variable when React 18 is stable as it can depend on `reactRoot` existing
shouldHydrate = false
} else {
const startTransition = (React as any).startTransition
startTransition(() => {
reactRoot.render(reactEl)
})
}
if (!reactRoot) {
// Unlike with createRoot, you don't need a separate root.render() call here
reactRoot = ReactDOM.hydrateRoot(domEl, reactEl)
// TODO: Remove shouldHydrate variable when React 18 is stable as it can depend on `reactRoot` existing
shouldHydrate = false
} else {
// The check for `.hydrate` is there to support React alternatives like preact
if (shouldHydrate) {
ReactDOM.hydrate(reactEl, domEl)
shouldHydrate = false
} else {
ReactDOM.render(reactEl, domEl)
}
const startTransition = (React as any).startTransition
startTransition(() => {
reactRoot.render(reactEl)
})
}
}
......
......@@ -969,19 +969,13 @@ export default function Image({
}
}
let imageSrcSetPropName = 'imagesrcset'
let imageSizesPropName = 'imagesizes'
if (process.env.__NEXT_REACT_ROOT) {
imageSrcSetPropName = 'imageSrcSet'
imageSizesPropName = 'imageSizes'
}
const linkProps: React.DetailedHTMLProps<
React.LinkHTMLAttributes<HTMLLinkElement>,
HTMLLinkElement
> = {
// Note: imagesrcset and imagesizes are not in the link element type with react 17.
[imageSrcSetPropName]: imgAttributes.srcSet,
[imageSizesPropName]: imgAttributes.sizes,
// @ts-expect-error upgrade react types to react 18
imageSrcSet: imgAttributes.srcSet,
imageSizes: imgAttributes.sizes,
crossOrigin: rest.crossOrigin,
}
......
......@@ -84,8 +84,8 @@
"peerDependencies": {
"fibers": ">= 3.1.0",
"node-sass": "^6.0.0 || ^7.0.0",
"react": "^18.0.0-0",
"react-dom": "^18.0.0-0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"sass": "^1.3.0"
},
"peerDependenciesMeta": {
......
......@@ -23,7 +23,6 @@ import {
streamToString,
} from './node-web-streams-helper'
import { ESCAPE_REGEX, htmlEscapeJsonString } from './htmlescape'
import { shouldUseReactRoot } from './utils'
import { matchSegment } from '../client/components/match-segments'
import {
FlightCSSManifest,
......@@ -671,7 +670,6 @@ function headersWithoutFlight(headers: IncomingHttpHeaders) {
}
async function renderToString(element: React.ReactElement) {
if (!shouldUseReactRoot) return ReactDOMServer.renderToString(element)
const renderStream = await ReactDOMServer.renderToReadableStream(element)
await renderStream.allReady
return streamToString(renderStream)
......
......@@ -1150,10 +1150,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const isBotRequest = isBot(req.headers['user-agent'] || '')
const isSupportedDocument =
typeof components.Document?.getInitialProps !== 'function' ||
// When concurrent features is enabled, the built-in `Document`
// component also supports dynamic HTML.
(!!process.env.__NEXT_REACT_ROOT &&
NEXT_BUILTIN_DOCUMENT in components.Document)
// The built-in `Document` component also supports dynamic HTML for concurrent mode.
NEXT_BUILTIN_DOCUMENT in components.Document
// Disable dynamic HTML in cases that we know it won't be generated,
// so that we can continue generating a cache key when possible.
......
......@@ -163,7 +163,6 @@ export default class HotReloader {
private webpackHotMiddleware?: WebpackHotMiddleware
private config: NextConfigComplete
public hasServerComponents: boolean
public hasReactRoot: boolean
public clientStats: webpack.Stats | null
public serverStats: webpack.Stats | null
public edgeServerStats: webpack.Stats | null
......@@ -216,8 +215,7 @@ export default class HotReloader {
this.serverPrevDocumentHash = null
this.config = config
this.hasReactRoot = !!process.env.__NEXT_REACT_ROOT
this.hasServerComponents = this.hasReactRoot && !!this.appDir
this.hasServerComponents = !!this.appDir
this.previewProps = previewProps
this.rewrites = rewrites
this.hotReloaderSpan = trace('hot-reloader', undefined, {
......@@ -456,7 +454,6 @@ export default class HotReloader {
dev: true,
buildId: this.buildId,
config: this.config,
hasReactRoot: this.hasReactRoot,
pagesDir: this.pagesDir,
rewrites: this.rewrites,
runWebpackSpan: this.hotReloaderSpan,
......@@ -521,7 +518,6 @@ export default class HotReloader {
pageExtensions: this.config.pageExtensions,
})
).client,
hasReactRoot: this.hasReactRoot,
})
const fallbackCompiler = webpack(fallbackConfig)
......
......@@ -547,7 +547,6 @@ export default class DevServer extends Server {
distDir: this.distDir,
isClient,
hasRewrites,
hasReactRoot: this.hotReloader?.hasReactRoot,
isNodeServer,
isEdgeServer,
})
......
......@@ -94,15 +94,10 @@ import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import { getClonableBody } from './body-streams'
import { checkIsManualRevalidate } from './api-utils'
import { shouldUseReactRoot } from './utils'
import ResponseCache from './response-cache'
import { IncrementalCache } from './lib/incremental-cache'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
if (shouldUseReactRoot) {
;(process.env as any).__NEXT_REACT_ROOT = 'true'
}
import { renderToHTMLOrFlight as appRenderToHTMLOrFlight } from './app-render'
export * from './base-server'
......
......@@ -11,7 +11,6 @@ import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
import { PHASE_PRODUCTION_SERVER } from '../shared/lib/constants'
import { IncomingMessage, ServerResponse } from 'http'
import { NextUrlWithParsedQuery } from './request-meta'
import { shouldUseReactRoot } from './utils'
import {
loadRequireHook,
overrideBuiltInReactPackages,
......@@ -211,10 +210,6 @@ function createServer(options: NextServerOptions): NextServer {
)
}
if (shouldUseReactRoot) {
;(process.env as any).__NEXT_REACT_ROOT = 'true'
}
return new NextServer(options)
}
......
......@@ -29,6 +29,7 @@ import type { ReactReadableStream } from './node-web-streams-helper'
import type { FontLoaderManifest } from '../build/webpack/plugins/font-loader-manifest-plugin'
import React from 'react'
import ReactDOMServer from 'react-dom/server.browser'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
import {
GSP_NO_RETURNED_VALUE,
......@@ -80,7 +81,6 @@ import {
} from './node-web-streams-helper'
import { ImageConfigContext } from '../shared/lib/image-config-context'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { shouldUseReactRoot } from './utils'
import { stripInternalQueries } from './internal-utils'
let tryGetPreviewData: typeof import('./api-utils/node').tryGetPreviewData
......@@ -88,9 +88,6 @@ let warn: typeof import('../build/output/log').warn
let postProcessHTML: typeof import('./post-process').postProcessHTML
const DOCTYPE = '<!DOCTYPE html>'
const ReactDOMServer = shouldUseReactRoot
? require('react-dom/server.browser')
: require('react-dom/server')
if (process.env.NEXT_RUNTIME !== 'edge') {
require('./node-polyfill-web-streams')
......@@ -109,17 +106,11 @@ function noRouter() {
}
async function renderToString(element: React.ReactElement) {
if (!shouldUseReactRoot) return ReactDOMServer.renderToString(element)
const renderStream = await ReactDOMServer.renderToReadableStream(element)
await renderStream.allReady
return streamToString(renderStream)
}
async function renderToStaticMarkup(element: React.ReactElement) {
if (!shouldUseReactRoot) return ReactDOMServer.renderToStaticMarkup(element)
return renderToString(element)
}
class ServerRouter implements NextRouter {
route: string
pathname: string
......@@ -420,30 +411,6 @@ export async function renderToHTML(
// next internal queries should be stripped out
stripInternalQueries(query)
const callMiddleware = async (method: string, args: any[], props = false) => {
let results: any = props ? {} : []
if ((Document as any)[`${method}Middleware`]) {
let middlewareFunc = await (Document as any)[`${method}Middleware`]
middlewareFunc = middlewareFunc.default || middlewareFunc
const curResults = await middlewareFunc(...args)
if (props) {
for (const result of curResults) {
results = {
...results,
...result,
}
}
} else {
results = curResults
}
}
return results
}
const headTags = (...args: any) => callMiddleware('headTags', args)
const isSSG = !!getStaticProps
const isBuildTimeSSG = isSSG && renderOpts.nextExport
const defaultAppGetInitialProps =
......@@ -1247,123 +1214,85 @@ export async function renderToHTML(
)
}
if (!process.env.__NEXT_REACT_ROOT) {
// Enabling react legacy rendering mode: __NEXT_REACT_ROOT = false
if (Document.getInitialProps) {
const documentInitialProps = await loadDocumentInitialProps()
if (documentInitialProps === null) return null
const { docProps, documentCtx } = documentInitialProps
return {
bodyResult: (suffix: string) =>
streamFromArray([docProps.html, suffix]),
documentElement: (htmlProps: HtmlProps) => (
<Document {...htmlProps} {...docProps} />
),
head: docProps.head,
headTags: await headTags(documentCtx),
styles: docProps.styles,
}
} else {
const content = renderContent(App, Component)
// for non-concurrent rendering we need to ensure App is rendered
// before _document so that updateHead is called/collected before
// rendering _document's head
const result = await renderToString(content)
const bodyResult = (suffix: string) => streamFromArray([result, suffix])
const styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
return {
bodyResult,
documentElement: () => (Document as any)(),
head,
headTags: [],
styles,
}
}
} else {
// Enabling react concurrent rendering mode: __NEXT_REACT_ROOT = true
const renderShell = async (
EnhancedApp: AppType,
EnhancedComponent: NextComponentType
) => {
const content = renderContent(EnhancedApp, EnhancedComponent)
return await renderToInitialStream({
ReactDOMServer,
element: content,
})
}
const createBodyResult = (
initialStream: ReactReadableStream,
suffix?: string
) => {
// this must be called inside bodyResult so appWrappers is
// up to date when `wrapApp` is called
const getServerInsertedHTML = async (): Promise<string> => {
return renderToString(styledJsxInsertedHTML())
}
// Always using react concurrent rendering mode with required react version 18.x
const renderShell = async (
EnhancedApp: AppType,
EnhancedComponent: NextComponentType
) => {
const content = renderContent(EnhancedApp, EnhancedComponent)
return await renderToInitialStream({
ReactDOMServer,
element: content,
})
}
return continueFromInitialStream(initialStream, {
suffix,
dataStream: serverComponentsInlinedTransformStream?.readable,
generateStaticHTML,
getServerInsertedHTML,
serverInsertedHTMLToHead: false,
})
const createBodyResult = (
initialStream: ReactReadableStream,
suffix?: string
) => {
// this must be called inside bodyResult so appWrappers is
// up to date when `wrapApp` is called
const getServerInsertedHTML = async (): Promise<string> => {
return renderToString(styledJsxInsertedHTML())
}
const hasDocumentGetInitialProps = !(
process.env.NEXT_RUNTIME === 'edge' || !Document.getInitialProps
)
return continueFromInitialStream(initialStream, {
suffix,
dataStream: serverComponentsInlinedTransformStream?.readable,
generateStaticHTML,
getServerInsertedHTML,
serverInsertedHTMLToHead: false,
})
}
let bodyResult: (s: string) => Promise<ReadableStream<Uint8Array>>
// If it has getInitialProps, we will render the shell in `renderPage`.
// Otherwise we do it right now.
let documentInitialPropsRes:
| {}
| Awaited<ReturnType<typeof loadDocumentInitialProps>>
if (hasDocumentGetInitialProps) {
documentInitialPropsRes = await loadDocumentInitialProps(renderShell)
if (documentInitialPropsRes === null) return null
const { docProps } = documentInitialPropsRes as any
// includes suffix in initial html stream
bodyResult = (suffix: string) =>
createBodyResult(streamFromArray([docProps.html, suffix]))
} else {
const stream = await renderShell(App, Component)
bodyResult = (suffix: string) => createBodyResult(stream, suffix)
documentInitialPropsRes = {}
}
const hasDocumentGetInitialProps = !(
process.env.NEXT_RUNTIME === 'edge' || !Document.getInitialProps
)
const { docProps } = (documentInitialPropsRes as any) || {}
const documentElement = (htmlProps: any) => {
if (process.env.NEXT_RUNTIME === 'edge') {
return (Document as any)()
} else {
return <Document {...htmlProps} {...docProps} />
}
}
let bodyResult: (s: string) => Promise<ReadableStream<Uint8Array>>
// If it has getInitialProps, we will render the shell in `renderPage`.
// Otherwise we do it right now.
let documentInitialPropsRes:
| {}
| Awaited<ReturnType<typeof loadDocumentInitialProps>>
if (hasDocumentGetInitialProps) {
documentInitialPropsRes = await loadDocumentInitialProps(renderShell)
if (documentInitialPropsRes === null) return null
const { docProps } = documentInitialPropsRes as any
// includes suffix in initial html stream
bodyResult = (suffix: string) =>
createBodyResult(streamFromArray([docProps.html, suffix]))
} else {
const stream = await renderShell(App, Component)
bodyResult = (suffix: string) => createBodyResult(stream, suffix)
documentInitialPropsRes = {}
}
let styles
if (hasDocumentGetInitialProps) {
styles = docProps.styles
head = docProps.head
const { docProps } = (documentInitialPropsRes as any) || {}
const documentElement = (htmlProps: any) => {
if (process.env.NEXT_RUNTIME === 'edge') {
return (Document as any)()
} else {
styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
return <Document {...htmlProps} {...docProps} />
}
}
return {
bodyResult,
documentElement,
head,
headTags: [],
styles,
}
let styles
if (hasDocumentGetInitialProps) {
styles = docProps.styles
head = docProps.head
} else {
styles = jsxStyleRegistry.styles()
jsxStyleRegistry.flush()
}
return {
bodyResult,
documentElement,
head,
headTags: [],
styles,
}
}
......@@ -1471,7 +1400,7 @@ export async function renderToHTML(
</AmpStateContext.Provider>
)
const documentHTML = await renderToStaticMarkup(document)
const documentHTML = await renderToString(document)
if (process.env.NODE_ENV !== 'production') {
const nonRenderedComponents = []
......
import React from 'react'
import { BLOCKED_PAGES } from '../shared/lib/constants'
export function isBlockedPage(pathname: string): boolean {
......@@ -15,6 +14,3 @@ export function cleanAmpPath(pathname: string): string {
pathname = pathname.replace(/\?$/, '')
return pathname
}
// When react version is >= 18 opt-in using reactRoot
export const shouldUseReactRoot = parseInt(React.version) >= 18
......@@ -109,13 +109,6 @@ export default function dynamic<P = {}>(
// Support for passing options, eg: dynamic(import('../hello-world'), {loading: () => <p>Loading something</p>})
loadableOptions = { ...loadableOptions, ...options }
// Error if Fizz rendering is not enabled and `suspense` option is set to true
if (!process.env.__NEXT_REACT_ROOT && loadableOptions.suspense) {
throw new Error(
`Invalid suspense option usage in next/dynamic. Read more: https://nextjs.org/docs/messages/invalid-dynamic-suspense`
)
}
if (loadableOptions.suspense) {
if (process.env.NODE_ENV !== 'production') {
/**
......
......@@ -156,10 +156,7 @@ function reduceComponents<T extends {} & WithInAmpMode>(
return React.cloneElement(c, newProps)
}
}
if (
process.env.NODE_ENV === 'development' &&
process.env.__NEXT_REACT_ROOT
) {
if (process.env.NODE_ENV === 'development') {
// omit JSON-LD structured data snippets from the warning
if (c.type === 'script' && c.props['type'] !== 'application/ld+json') {
const srcMessage = c.props['src']
......
......@@ -21,13 +21,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
// https://github.com/jamiebuilds/react-loadable/blob/v5.5.0/src/index.js
// Modified to be compatible with webpack 4 / Next.js
import React from 'react'
import React, { useSyncExternalStore } from 'react'
import { LoadableContext } from './loadable-context'
const { useSyncExternalStore } = process.env.__NEXT_REACT_ROOT
? require('react')
: require('use-sync-external-store/shim')
const ALL_INITIALIZERS = []
const READY_INITIALIZERS = []
let initialized = false
......
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