Unverified Commit 6f2e1400 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix pages react alias (#50128)

Fix react and react-dom aliases are not properly set for `pages/`

* Remove alias react-dom internals to `{}` in edge runtime as we're using server rendering stub as alias
* Add `react$`, `react-dom$` missing aliases
* Only apply alias to builtin react/react-dom when it's app dir assets.
* Add `react|react-dom/package.json` resolving to require-hook
* Fix hmr issue that sometimes it will perform a reload when a hard navigation is triggered
parent f4bb4aa7
...@@ -66,6 +66,11 @@ import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plu ...@@ -66,6 +66,11 @@ import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plu
import { getSupportedBrowsers } from './utils' import { getSupportedBrowsers } from './utils'
import { METADATA_RESOURCE_QUERY } from './webpack/loaders/metadata/discover' import { METADATA_RESOURCE_QUERY } from './webpack/loaders/metadata/discover'
type ExcludesFalse = <T>(x: T | false) => x is T
type ClientEntries = {
[key: string]: string | string[]
}
const EXTERNAL_PACKAGES = const EXTERNAL_PACKAGES =
require('../lib/server-external-packages.json') as string[] require('../lib/server-external-packages.json') as string[]
...@@ -384,7 +389,42 @@ export function getDefineEnv({ ...@@ -384,7 +389,42 @@ export function getDefineEnv({
} }
} }
type ExcludesFalse = <T>(x: T | false) => x is T function createReactAliases(
bundledReactChannel: string,
opts: {
reactSharedSubset: boolean
reactDomServerRenderingStub: boolean
}
) {
const alias = {
react$: `next/dist/compiled/react${bundledReactChannel}`,
'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}`,
'react/jsx-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-runtime`,
'react/jsx-dev-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-dev-runtime`,
'react-dom/server$': `next/dist/compiled/react-dom${bundledReactChannel}/server$`,
'react-dom/server.edge$': `next/dist/compiled/react-dom${bundledReactChannel}/server.edge`,
'react-dom/server.browser$': `next/dist/compiled/react-dom${bundledReactChannel}/server.browser`,
'react-server-dom-webpack/client$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client`,
'react-server-dom-webpack/client.edge$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client.edge`,
'react-server-dom-webpack/server.edge$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.edge`,
'react-server-dom-webpack/server.node$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.node`,
}
if (opts.reactSharedSubset) {
alias[
'react$'
] = `next/dist/compiled/react${bundledReactChannel}/react.shared-subset`
}
// Use server rendering stub for RSC
// x-ref: https://github.com/facebook/react/pull/25436
if (opts.reactDomServerRenderingStub) {
alias[
'react-dom$'
] = `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub`
}
return alias
}
const devtoolRevertWarning = execOnce( const devtoolRevertWarning = execOnce(
(devtool: webpack.Configuration['devtool']) => { (devtool: webpack.Configuration['devtool']) => {
...@@ -436,10 +476,6 @@ function getOptimizedAliases(): { [pkg: string]: string } { ...@@ -436,10 +476,6 @@ function getOptimizedAliases(): { [pkg: string]: string } {
) )
} }
type ClientEntries = {
[key: string]: string | string[]
}
export function attachReactRefresh( export function attachReactRefresh(
webpackConfig: webpack.Configuration, webpackConfig: webpack.Configuration,
targetLoader: webpack.RuleSetUseItem targetLoader: webpack.RuleSetUseItem
...@@ -1519,10 +1555,6 @@ export default async function getBaseWebpackConfig( ...@@ -1519,10 +1555,6 @@ export default async function getBaseWebpackConfig(
'@builder.io/partytown': '{}', '@builder.io/partytown': '{}',
'next/dist/compiled/etag': '{}', 'next/dist/compiled/etag': '{}',
'next/dist/compiled/chalk': '{}', 'next/dist/compiled/chalk': '{}',
'./cjs/react-dom-server-legacy.browser.production.min.js':
'{}',
'./cjs/react-dom-server-legacy.browser.development.js':
'{}',
}, },
getEdgePolyfilledModules(), getEdgePolyfilledModules(),
handleWebpackExternalForEdgeRuntime, handleWebpackExternalForEdgeRuntime,
...@@ -1822,13 +1854,10 @@ export default async function getBaseWebpackConfig( ...@@ -1822,13 +1854,10 @@ export default async function getBaseWebpackConfig(
[require.resolve('next/dynamic')]: require.resolve( [require.resolve('next/dynamic')]: require.resolve(
'next/dist/shared/lib/app-dynamic' 'next/dist/shared/lib/app-dynamic'
), ),
'react/jsx-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-runtime`, ...createReactAliases(bundledReactChannel, {
'react/jsx-dev-runtime$': `next/dist/compiled/react${bundledReactChannel}/jsx-dev-runtime`, reactSharedSubset: false,
'react-dom/server.edge$': `next/dist/compiled/react-dom${bundledReactChannel}/server.edge`, reactDomServerRenderingStub: false,
'react-server-dom-webpack/client$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client`, }),
'react-server-dom-webpack/client.edge$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/client.edge`,
'react-server-dom-webpack/server.edge$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.edge`,
'react-server-dom-webpack/server.node$': `next/dist/compiled/react-server-dom-webpack${bundledReactChannel}/server.node`,
}, },
}, },
}, },
...@@ -1856,8 +1885,10 @@ export default async function getBaseWebpackConfig( ...@@ -1856,8 +1885,10 @@ export default async function getBaseWebpackConfig(
// If missing the alias override here, the default alias will be used which aliases // If missing the alias override here, the default alias will be used which aliases
// react to the direct file path, not the package name. In that case the condition // react to the direct file path, not the package name. In that case the condition
// will be ignored completely. // will be ignored completely.
react: `next/dist/compiled/react${bundledReactChannel}/react.shared-subset`, ...createReactAliases(bundledReactChannel, {
'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub`, reactSharedSubset: true,
reactDomServerRenderingStub: true,
}),
}, },
}, },
use: { use: {
...@@ -1920,36 +1951,39 @@ export default async function getBaseWebpackConfig( ...@@ -1920,36 +1951,39 @@ export default async function getBaseWebpackConfig(
// It needs `conditionNames` here to require the proper asset, // It needs `conditionNames` here to require the proper asset,
// when react is acting as dependency of compiled/react-dom. // when react is acting as dependency of compiled/react-dom.
alias: { alias: {
react: `next/dist/compiled/react${bundledReactChannel}/react.shared-subset`, ...createReactAliases(bundledReactChannel, {
// Use server rendering stub for RSC reactSharedSubset: true,
// x-ref: https://github.com/facebook/react/pull/25436 reactDomServerRenderingStub: true,
'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub`, }),
}, },
}, },
}, },
{ {
issuerLayer: WEBPACK_LAYERS.client,
test: codeCondition.test, test: codeCondition.test,
issuerLayer: WEBPACK_LAYERS.client,
resolve: { resolve: {
alias: { alias: {
react: `next/dist/compiled/react${bundledReactChannel}`, ...createReactAliases(bundledReactChannel, {
'react-dom$': `next/dist/compiled/react-dom${bundledReactChannel}/server-rendering-stub`, reactSharedSubset: false,
reactDomServerRenderingStub: true,
}),
},
}, },
}, },
],
}, },
{ {
test: codeCondition.test, test: codeCondition.test,
issuerLayer: WEBPACK_LAYERS.appClient,
resolve: { resolve: {
alias: { alias: {
react: `next/dist/compiled/react${bundledReactChannel}`, ...createReactAliases(bundledReactChannel, {
'react-dom$': reactProductionProfiling // Only alias server rendering stub in client SSR layer.
? `next/dist/compiled/react-dom${bundledReactChannel}/cjs/react-dom.profiling.min` reactSharedSubset: false,
: `next/dist/compiled/react-dom${bundledReactChannel}`, reactDomServerRenderingStub: false,
'react-dom/client$': `next/dist/compiled/react-dom${bundledReactChannel}/client`, }),
},
}, },
}, },
],
}, },
] ]
: []), : []),
......
...@@ -180,6 +180,7 @@ export default class HotReloader { ...@@ -180,6 +180,7 @@ export default class HotReloader {
private clientError: Error | null = null private clientError: Error | null = null
private serverError: Error | null = null private serverError: Error | null = null
private serverPrevDocumentHash: string | null private serverPrevDocumentHash: string | null
private serverChunkNames?: Set<string>
private prevChunkNames?: Set<any> private prevChunkNames?: Set<any>
private onDemandEntries?: ReturnType<typeof onDemandEntryHandler> private onDemandEntries?: ReturnType<typeof onDemandEntryHandler>
private previewProps: __ApiPreviewProps private previewProps: __ApiPreviewProps
...@@ -1050,6 +1051,7 @@ export default class HotReloader { ...@@ -1050,6 +1051,7 @@ export default class HotReloader {
(err: Error) => { (err: Error) => {
this.serverError = err this.serverError = err
this.serverStats = null this.serverStats = null
this.serverChunkNames = undefined
} }
) )
...@@ -1093,16 +1095,38 @@ export default class HotReloader { ...@@ -1093,16 +1095,38 @@ export default class HotReloader {
return return
} }
// As document chunk will change if new app pages are joined,
// since react bundle is different it will effect the chunk hash.
// So we diff the chunk changes, if there's only new app page chunk joins,
// then we don't trigger a reload by checking pages/_document chunk change.
if (this.appDir) {
const chunkNames = new Set(compilation.namedChunks.keys())
const diffChunkNames = difference<string>(
this.serverChunkNames || new Set(),
chunkNames
)
if (
diffChunkNames.length === 0 ||
diffChunkNames.every((chunkName) => chunkName.startsWith('app/'))
) {
return
}
this.serverChunkNames = chunkNames
}
// Notify reload to reload the page, as _document.js was changed (different hash) // Notify reload to reload the page, as _document.js was changed (different hash)
this.send('reloadPage') this.send('reloadPage')
this.serverPrevDocumentHash = documentChunk.hash || null this.serverPrevDocumentHash = documentChunk.hash || null
} }
) )
this.multiCompiler.hooks.done.tap('NextjsHotReloaderForServer', () => { this.multiCompiler.hooks.done.tap('NextjsHotReloaderForServer', () => {
const serverOnlyChanges = difference<string>( const serverOnlyChanges = difference<string>(
changedServerPages, changedServerPages,
changedClientPages changedClientPages
) )
const edgeServerOnlyChanges = difference<string>( const edgeServerOnlyChanges = difference<string>(
changedEdgeServerPages, changedEdgeServerPages,
changedClientPages changedClientPages
......
...@@ -54,6 +54,16 @@ function overrideReact() { ...@@ -54,6 +54,16 @@ function overrideReact() {
`next/dist/compiled/react-dom-experimental/server-rendering-stub` `next/dist/compiled/react-dom-experimental/server-rendering-stub`
), ),
], ],
[
'react/package.json',
require.resolve(`next/dist/compiled/react-experimental/package.json`),
],
[
'react-dom/package.json',
require.resolve(
`next/dist/compiled/react-dom-experimental/package.json`
),
],
[ [
'react-dom/client', 'react-dom/client',
require.resolve(`next/dist/compiled/react-dom-experimental/client`), require.resolve(`next/dist/compiled/react-dom-experimental/client`),
...@@ -102,6 +112,10 @@ function overrideReact() { ...@@ -102,6 +112,10 @@ function overrideReact() {
} else { } else {
addHookAliases([ addHookAliases([
['react', require.resolve(`next/dist/compiled/react`)], ['react', require.resolve(`next/dist/compiled/react`)],
[
'react/package.json',
require.resolve(`next/dist/compiled/react/package.json`),
],
[ [
'react/jsx-runtime', 'react/jsx-runtime',
require.resolve(`next/dist/compiled/react/jsx-runtime`), require.resolve(`next/dist/compiled/react/jsx-runtime`),
...@@ -114,6 +128,10 @@ function overrideReact() { ...@@ -114,6 +128,10 @@ function overrideReact() {
'react-dom', 'react-dom',
require.resolve(`next/dist/compiled/react-dom/server-rendering-stub`), require.resolve(`next/dist/compiled/react-dom/server-rendering-stub`),
], ],
[
'react-dom/package.json',
require.resolve(`next/dist/compiled/react-dom/package.json`),
],
[ [
'react-dom/client', 'react-dom/client',
require.resolve(`next/dist/compiled/react-dom/client`), require.resolve(`next/dist/compiled/react-dom/client`),
......
export const runtime = 'experimental-edge' export const runtime = 'edge'
export default (req) => { export default (req) => {
return Response.json(Object.fromEntries(req.headers.entries()), { return Response.json(Object.fromEntries(req.headers.entries()), {
......
import React from 'react' import React from 'react'
import ReactDOM from 'react-dom'
import ReactDOMServer from 'react-dom/server.browser'
export default function Page() { export default function Page() {
return <div>{'version=' + React.version}</div> return (
<div>
<p id="react">{'React.version=' + React.version}</p>
<p id="react-dom">{'ReactDOM.version=' + ReactDOM.version}</p>
<p id="react-dom-server">
{'ReactDOMServer.version=' + ReactDOMServer.version}
</p>
</div>
)
} }
import React from 'react'
import ReactDOM from 'react-dom'
import ReactDOMServer from 'react-dom/server'
export default function Page() {
return (
<div>
<p id="react">{'React.version=' + React.version}</p>
<p id="react-dom">{'ReactDOM.version=' + ReactDOM.version}</p>
<p id="react-dom-server">
{'ReactDOMServer.version=' + ReactDOMServer.version}
</p>
</div>
)
}
export const runtime = 'experimental-edge'
import React from 'react' import React from 'react'
import ReactDOM from 'react-dom'
import ReactDOMServer from 'react-dom/server'
export default function Page() { export default function Page() {
return <div>{'version=' + React.version}</div> return (
<div>
<p id="react">{'React.version=' + React.version}</p>
<p id="react-dom">{'ReactDOM.version=' + ReactDOM.version}</p>
<p id="react-dom-server">
{'ReactDOMServer.version=' + ReactDOMServer.version}
</p>
</div>
)
} }
...@@ -19,19 +19,9 @@ createNextDescribe( ...@@ -19,19 +19,9 @@ createNextDescribe(
{ {
files: __dirname, files: __dirname,
dependencies: { dependencies: {
'styled-components': '6.0.0-beta.5', 'styled-components': 'latest',
'server-only': 'latest', 'server-only': 'latest',
}, },
packageJson: {
scripts: {
build: 'next build',
dev: 'next dev',
start: 'next start',
},
},
installCommand: 'yarn',
startCommand: (global as any).isNextDev ? 'yarn dev' : 'yarn start',
buildCommand: 'yarn build',
}, },
({ next, isNextDev, isNextStart }) => { ({ next, isNextDev, isNextStart }) => {
if (isNextDev) { if (isNextDev) {
...@@ -437,18 +427,72 @@ createNextDescribe( ...@@ -437,18 +427,72 @@ createNextDescribe(
}) })
it('should use stable react for pages', async () => { it('should use stable react for pages', async () => {
const resPages = await next.fetch('/pages-react') const ssrPaths = ['/pages-react', '/pages-react-edge', '/app-react']
const versionPages = (await resPages.text()).match( const promises = ssrPaths.map(async (pathname) => {
/<div>version=([^<]+)<\/div>/ const resPages$ = await next.render$(pathname)
)?.[1] const ssrPagesReactVersions = [
await resPages$('#react').text(),
const resApp = await next.fetch('/app-react') await resPages$('#react-dom').text(),
const versionApp = (await resApp.text()).match( await resPages$('#react-dom-server').text(),
/<div>version=([^<]+)<\/div>/ ]
)?.[1]
ssrPagesReactVersions.forEach((version) => {
expect(versionPages).not.toInclude('-canary-') if (pathname === '/app-react') {
expect(versionApp).toInclude('-canary-') expect(version).toMatch('-canary-')
} else {
expect(version).not.toMatch('-canary-')
}
})
})
await Promise.all(promises)
const resApp$ = await next.render$('/app-react')
const ssrAppReactVersions = [
await resApp$('#react').text(),
await resApp$('#react-dom').text(),
await resApp$('#react-dom-server').text(),
]
ssrAppReactVersions.forEach((version) =>
expect(version).toMatch('-canary-')
)
const browser = await next.browser('/pages-react')
const browserPagesReactVersions = await browser.eval(`
[
document.querySelector('#react').innerText,
document.querySelector('#react-dom').innerText,
document.querySelector('#react-dom-server').innerText,
]
`)
await browser.loadPage(next.url + '/edge-pages-react')
const browserEdgePagesReactVersions = await browser.eval(`
[
document.querySelector('#react').innerText,
document.querySelector('#react-dom').innerText,
document.querySelector('#react-dom-server').innerText,
]
`)
await browser.loadPage(next.url + '/app-react')
const browserAppReactVersions = await browser.eval(`
[
document.querySelector('#react').innerText,
document.querySelector('#react-dom').innerText,
document.querySelector('#react-dom-server').innerText,
]
`)
browserPagesReactVersions.forEach((version) =>
expect(version).not.toMatch('-canary-')
)
browserEdgePagesReactVersions.forEach((version) =>
expect(version).not.toMatch('-canary-')
)
browserAppReactVersions.forEach((version) =>
expect(version).toMatch('-canary-')
)
}) })
// disable this flaky test // disable this flaky test
......
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