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