Unverified Commit 0f2845d2 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

Support React 18 in Pages Router (#69484)

Pages router (`/pages`) will continue to support React 18 not the React
19 RC. Current thinking is that we'll add support for React 19 in Pages
Router once 19 is stable.

This does not affect App Router (`/app`) which continues to use the
latest React Canary (i.e. React 19).

https://github.com/vercel/next.js/pull/65058 is required reading to
understand the changes in this PR

---------
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent 644b6c61
......@@ -7,8 +7,8 @@
},
"dependencies": {
"next": "canary",
"react": "19.0.0-rc-7771d3a7-20240827",
"react-dom": "19.0.0-rc-7771d3a7-20240827"
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/node": "20.12.12",
......
......@@ -206,10 +206,10 @@
"pretty-bytes": "5.3.0",
"pretty-ms": "7.0.0",
"random-seed": "0.3.0",
"react": "19.0.0-rc-7771d3a7-20240827",
"react": "18.3.1",
"react-17": "npm:react@17.0.2",
"react-builtin": "npm:react@19.0.0-rc-7771d3a7-20240827",
"react-dom": "19.0.0-rc-7771d3a7-20240827",
"react-dom": "18.3.1",
"react-dom-17": "npm:react-dom@17.0.2",
"react-dom-builtin": "npm:react-dom@19.0.0-rc-7771d3a7-20240827",
"react-dom-experimental-builtin": "npm:react-dom@0.0.0-experimental-7771d3a7-20240827",
......@@ -269,10 +269,10 @@
"@babel/traverse": "7.22.5",
"@types/react": "npm:types-react@19.0.0-rc.0",
"@types/react-dom": "npm:types-react-dom@19.0.0-rc.0",
"react": "19.0.0-rc-7771d3a7-20240827",
"react-dom": "19.0.0-rc-7771d3a7-20240827",
"react-is": "19.0.0-rc-7771d3a7-20240827",
"scheduler": "0.25.0-rc-7771d3a7-20240827"
"react": "18.3.1",
"react-dom": "18.3.1",
"react-is": "18.3.1",
"scheduler": "0.23.2"
},
"patchedDependencies": {
"webpack-sources@3.2.3": "patches/webpack-sources@3.2.3.patch"
......
......@@ -13,7 +13,7 @@ import { GetTemplateFileArgs, InstallTemplateArgs } from "./types";
// Do not rename or format. sync-react script relies on this line.
// prettier-ignore
const nextjsReactPeerVersion = "19.0.0-rc-7771d3a7-20240827";
const nextjsReactPeerVersion = "^18.2.0";
/**
* Get the file path for a given file in a template, e.g. "next.config.js".
......
......@@ -108,8 +108,8 @@
"@opentelemetry/api": "^1.1.0",
"@playwright/test": "^1.41.2",
"babel-plugin-react-compiler": "*",
"react": "19.0.0-rc-7771d3a7-20240827",
"react-dom": "19.0.0-rc-7771d3a7-20240827",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"sass": "^1.3.0"
},
"peerDependenciesMeta": {
......
......@@ -107,8 +107,8 @@ const NEXT_PROJECT_ROOT_DIST_CLIENT = path.join(
'client'
)
if (parseInt(React.version) < 19) {
throw new Error('Next.js requires react >= 19.0.0 to be installed.')
if (parseInt(React.version) !== 18) {
throw new Error('Next.js requires react@^18.2.0 to be installed.')
}
export const babelIncludeRegexes: RegExp[] = [
......
......@@ -238,7 +238,6 @@ export function Errors({
)
const errorDetails: HydrationErrorState = (error as any).details || {}
const notes = errorDetails.notes || ''
const [warningTemplate, serverContent, clientContent] =
errorDetails.warning || [null, '', '']
......@@ -252,6 +251,7 @@ export function Errors({
.replace(/^Warning: /, '')
.replace(/^Error: /, '')
: null
const notes = isAppDir ? errorDetails.notes || '' : hydrationWarning
return (
<Overlay>
......@@ -307,7 +307,9 @@ export function Errors({
{/* If there's hydration warning, skip displaying the error name */}
{hydrationWarning ? '' : error.name + ': '}
<HotlinkedText
text={hydrationWarning || error.message}
text={
isAppDir ? hydrationWarning || error.message : error.message
}
matcher={isNextjsLink}
/>
</p>
......
......@@ -66,7 +66,7 @@ export function PseudoHtmlDiff({
firstContent: string
secondContent: string
reactOutputComponentDiff: string | undefined
hydrationMismatchType: 'tag' | 'text'
hydrationMismatchType: 'tag' | 'text' | 'text-in-tag'
} & React.HTMLAttributes<HTMLPreElement>) {
const isHtmlTagsWarning = hydrationMismatchType === 'tag'
const isReactHydrationDiff = !!reactOutputComponentDiff
......
......@@ -23,15 +23,42 @@ const htmlTagsWarnings = new Set([
"In HTML, whitespace text nodes cannot be a child of <%s>. Make sure you don't have any extra whitespace between tags on each line of your source code.\nThis will cause a hydration error.",
])
export const getHydrationWarningType = (msg: NullableText): 'tag' | 'text' => {
// In React 18, the warning message is prefixed with "Warning: "
const normalizeWarningMessage = (msg: string) => msg.replace(/^Warning: /, '')
// Note: React 18 only
const textAndTagsMismatchWarnings = new Set([
'Warning: Expected server HTML to contain a matching text node for "%s" in <%s>.%s',
'Warning: Did not expect server HTML to contain the text node "%s" in <%s>.%s',
])
// Note: React 18 only
const textMismatchWarning =
'Warning: Text content did not match. Server: "%s" Client: "%s"%s'
const isTextMismatchWarning = (msg: NullableText) => textMismatchWarning === msg
const isTextInTagsMismatchWarning = (msg: NullableText) =>
Boolean(msg && textAndTagsMismatchWarnings.has(msg))
export const getHydrationWarningType = (
msg: NullableText
): 'tag' | 'text' | 'text-in-tag' => {
if (isHtmlTagsWarning(msg)) return 'tag'
return 'text'
}
const isHtmlTagsWarning = (msg: NullableText) =>
Boolean(msg && htmlTagsWarnings.has(msg))
const isHtmlTagsWarning = (msg: NullableText) => {
if (msg && typeof msg === 'string') {
return htmlTagsWarnings.has(normalizeWarningMessage(msg))
}
return false
}
const isKnownHydrationWarning = (msg: NullableText) => isHtmlTagsWarning(msg)
const isKnownHydrationWarning = (msg: NullableText) =>
isHtmlTagsWarning(msg) ||
isTextInTagsMismatchWarning(msg) ||
isTextMismatchWarning(msg)
export const getReactHydrationDiffSegments = (msg: NullableText) => {
if (msg) {
......@@ -51,14 +78,18 @@ export const getReactHydrationDiffSegments = (msg: NullableText) => {
export function storeHydrationErrorStateFromConsoleArgs(...args: any[]) {
const [msg, serverContent, clientContent, componentStack] = args
if (isKnownHydrationWarning(msg)) {
hydrationErrorState.warning = [
// remove the last %s from the message
msg,
serverContent,
clientContent,
]
hydrationErrorState.warning = [msg, serverContent, clientContent]
hydrationErrorState.componentStack = componentStack
hydrationErrorState.serverContent = serverContent
hydrationErrorState.clientContent = clientContent
return [
...args,
// We tack on the hydration error message to the console.error message so that
// it matches the error we display in the redbox overlay
`\nSee more info here: https://nextjs.org/docs/messages/react-hydration-error`,
]
}
return args
}
......@@ -52,11 +52,13 @@ function handleError(error: unknown) {
let origConsoleError = console.error
function nextJsHandleConsoleError(...args: any[]) {
// To support React 19, this will need to be updated as follows:
// const error = process.env.NODE_ENV !== 'production' ? args[1] : args[0]
// See https://github.com/facebook/react/blob/d50323eb845c5fde0d720cae888bf35dedd05506/packages/react-reconciler/src/ReactFiberErrorLogger.js#L78
const error = process.env.NODE_ENV !== 'production' ? args[1] : args[0]
storeHydrationErrorStateFromConsoleArgs(...args)
const error = args[0]
const errorArgs = storeHydrationErrorStateFromConsoleArgs(...args)
handleError(error)
origConsoleError.apply(window.console, args)
origConsoleError.apply(window.console, errorArgs)
}
function onUnhandledError(event: ErrorEvent) {
......
......@@ -9,6 +9,8 @@ import React, {
useState,
type JSX,
} from 'react'
import * as ReactDOM from 'react-dom'
import Head from '../../shared/lib/head'
import {
imageConfigDefault,
VALID_LOADERS,
......@@ -26,6 +28,8 @@ function normalizeSrc(src: string): string {
return src[0] === '/' ? src.slice(1) : src
}
const supportsFloat = typeof ReactDOM.preload === 'function'
const configEnv = process.env.__NEXT_IMAGE_OPTS as any as ImageConfigComplete
const loadedImageURLs = new Set<string>()
const allImgs = new Map<
......@@ -978,6 +982,20 @@ export default function Image({
}
}
const linkProps:
| React.DetailedHTMLProps<
React.LinkHTMLAttributes<HTMLLinkElement>,
HTMLLinkElement
>
| undefined = supportsFloat
? undefined
: {
imageSrcSet: imgAttributes.srcSet,
imageSizes: imgAttributes.sizes,
crossOrigin: rest.crossOrigin,
referrerPolicy: rest.referrerPolicy,
}
const useLayoutEffect =
typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect
const onLoadingCompleteRef = useRef(onLoadingComplete)
......@@ -1044,6 +1062,27 @@ export default function Image({
) : null}
<ImageElement {...imgElementArgs} />
</span>
{!supportsFloat && priority ? (
// Note how we omit the `href` attribute, as it would only be relevant
// for browsers that do not support `imagesrcset`, and in those cases
// it would likely cause the incorrect image to be preloaded.
//
// https://html.spec.whatwg.org/multipage/semantics.html#attr-link-imagesrcset
<Head>
<link
key={
'__nimg-' +
imgAttributes.src +
imgAttributes.srcSet +
imgAttributes.sizes
}
rel="preload"
as="image"
href={imgAttributes.srcSet ? undefined : imgAttributes.src}
{...linkProps}
/>
</Head>
) : null}
</>
)
}
import { useMemo, type Ref } from 'react'
import { useMemo, useRef, type Ref } from 'react'
// This is a compatibility hook to support React 18 and 19 refs.
// In 19, a cleanup function from refs may be returned.
// In 18, returning a cleanup function creates a warning.
// Since we take userspace refs, we don't know ahead of time if a cleanup function will be returned.
// This implements cleanup functions with the old behavior in 18.
// We know refs are always called alternating with `null` and then `T`.
// So a call with `null` means we need to call the previous cleanup functions.
export function useMergedRef<TElement>(
refA: Ref<TElement>,
refB: Ref<TElement>
): Ref<TElement> {
return useMemo(() => mergeRefs(refA, refB), [refA, refB])
}
const cleanupA = useRef<() => void>(() => {})
const cleanupB = useRef<() => void>(() => {})
export function mergeRefs<TElement>(
refA: Ref<TElement>,
refB: Ref<TElement>
): Ref<TElement> {
if (!refA || !refB) {
return refA || refB
}
return (current: TElement) => {
const cleanupA = applyRef(refA, current)
const cleanupB = applyRef(refB, current)
return useMemo(() => {
if (!refA || !refB) {
return refA || refB
}
return () => {
cleanupA()
cleanupB()
return (current: TElement | null): void => {
if (current === null) {
cleanupA.current()
cleanupB.current()
} else {
cleanupA.current = applyRef(refA, current)
cleanupB.current = applyRef(refB, current)
}
}
}
}, [refA, refB])
}
function applyRef<TElement>(
......
(()=>{var t={583:t=>{function n(t,i){for(var _ in i)t[_]=i[_];return t}t.exports=function(t){var i=[];function u(t){for(var _=[],a=0;a<i.length;a++)i[a]===t?t=null:_.push(i[a]);i=_}function e(_,a,f){t=a?_:n(n({},t),_);for(var o=i,c=0;c<o.length;c++)o[c](t,f)}return t=t||{},{action:function(i){function r(t){e(t,!1,i)}return function(){for(var _=arguments,a=[t],f=0;f<arguments.length;f++)a.push(_[f]);var o=i.apply(this,a);if(null!=o)return o.then?o.then(r):r(o)}},setState:e,subscribe:function(t){return i.push(t),function(){u(t)}},unsubscribe:u,getState:function(){return t}}}}};var i={};function __nccwpck_require__(_){var a=i[_];if(a!==undefined){return a.exports}var f=i[_]={exports:{}};var o=true;try{t[_](f,f.exports,__nccwpck_require__);o=false}finally{if(o)delete i[_]}return f.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var _=__nccwpck_require__(583);module.exports=_})();
\ No newline at end of file
(()=>{var t={302:t=>{function n(t,i){for(var _ in i)t[_]=i[_];return t}t.exports=function(t){var i=[];function u(t){for(var _=[],a=0;a<i.length;a++)i[a]===t?t=null:_.push(i[a]);i=_}function e(_,a,f){t=a?_:n(n({},t),_);for(var o=i,c=0;c<o.length;c++)o[c](t,f)}return t=t||{},{action:function(i){function r(t){e(t,!1,i)}return function(){for(var _=arguments,a=[t],f=0;f<arguments.length;f++)a.push(_[f]);var o=i.apply(this,a);if(null!=o)return o.then?o.then(r):r(o)}},setState:e,subscribe:function(t){return i.push(t),function(){u(t)}},unsubscribe:u,getState:function(){return t}}}}};var i={};function __nccwpck_require__(_){var a=i[_];if(a!==undefined){return a.exports}var f=i[_]={exports:{}};var o=true;try{t[_](f,f.exports,__nccwpck_require__);o=false}finally{if(o)delete i[_]}return f.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var _=__nccwpck_require__(302);module.exports=_})();
\ No newline at end of file
......@@ -40,7 +40,7 @@ import type { Revalidate, SwrDelta } from './lib/revalidate'
import type { COMPILER_NAMES } from '../shared/lib/constants'
import React, { type JSX } from 'react'
import ReactDOMServerEdge from 'react-dom/server.edge'
import ReactDOMServerBrowser from 'react-dom/server.browser'
import { StyleRegistry, createStyleRegistry } from 'styled-jsx'
import {
GSP_NO_RETURNED_VALUE,
......@@ -127,7 +127,8 @@ function noRouter() {
}
async function renderToString(element: React.ReactElement) {
const renderStream = await ReactDOMServerEdge.renderToReadableStream(element)
const renderStream =
await ReactDOMServerBrowser.renderToReadableStream(element)
await renderStream.allReady
return streamToString(renderStream)
}
......@@ -1322,7 +1323,7 @@ export async function renderToHTMLImpl(
) => {
const content = renderContent(EnhancedApp, EnhancedComponent)
return await renderToInitialFizzStream({
ReactDOMServer: ReactDOMServerEdge,
ReactDOMServer: ReactDOMServerBrowser,
element: content,
})
}
......
......@@ -70,6 +70,10 @@ declare module 'react-dom/server.edge' {
>
}
declare module 'react-dom/server.browser' {
export * from 'react-dom/server.edge'
}
declare module 'react-dom/static.edge' {
import type { JSX } from 'react'
/**
......
......@@ -13,6 +13,7 @@ const pagesExternals = [
'react-dom/package.json',
'react-dom/client',
'react-dom/server',
'react-dom/server.browser',
'react-dom/server.edge',
'react-server-dom-webpack/client',
'react-server-dom-webpack/client.edge',
......
This diff is collapsed.
......@@ -18,9 +18,10 @@ const exec = promisify(execOrig)
const core = require('@actions/core')
const { getTestFilter } = require('./test/get-test-filter')
// TODO: Base this off of test matrix
// Do not rename or format. sync-react script relies on this line.
// prettier-ignore
const nextjsReactPeerVersion = "19.0.0-rc-7771d3a7-20240827";
const nextjsReactPeerVersion = "^18.2.0";
let argv = require('yargs/yargs')(process.argv.slice(2))
.string('type')
......
......@@ -4,8 +4,8 @@
"license": "MIT",
"dependencies": {
"next": "latest",
"react": "19.0.0-rc-7771d3a7-20240827",
"react-dom": "19.0.0-rc-7771d3a7-20240827"
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"engines": {
"node": ">=18.18.0"
......
......@@ -4,7 +4,8 @@ import { FileRef, nextTestSetup } from 'e2e-utils'
import { outdent } from 'outdent'
import path from 'path'
describe('Error overlay for hydration errors (React 19)', () => {
// TODO: Enable once React 19 support is added to pages.
describe.skip('Error overlay for hydration errors (React 19)', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
skipStart: true,
......
......@@ -4,8 +4,7 @@ import { FileRef, nextTestSetup } from 'e2e-utils'
import { outdent } from 'outdent'
import path from 'path'
// TODO: Enable this test once react 18 is supported for pages router
describe.skip('Error overlay for hydration errors (React 18)', () => {
describe('Error overlay for hydration errors (React 18)', () => {
const { next } = nextTestSetup({
files: new FileRef(path.join(__dirname, 'fixtures', 'default-template')),
dependencies: {
......@@ -38,7 +37,7 @@ describe.skip('Error overlay for hydration errors (React 18)', () => {
await session.assertHasRedbox()
expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`
"Error: Text content does not match server-rendered HTML.
"Text content does not match server-rendered HTML.
See more info here: https://nextjs.org/docs/messages/react-hydration-error"
`)
......
......@@ -18,6 +18,8 @@ import { NextInstance } from 'e2e-utils'
import { outdent } from 'outdent'
import type { NextConfig } from 'next'
const isReact18 = true
describe.each([
{ basePath: '', assetPrefix: '' },
{ basePath: '', assetPrefix: '/asset-prefix' },
......@@ -41,11 +43,14 @@ describe.each([
})
await retry(async () => {
const logs = await browser.log()
expect(logs).toEqual(
expect.arrayContaining([
{
message: expect.stringContaining(
'https://react.dev/link/hydration-mismatch'
isReact18
? 'https://nextjs.org/docs/messages/react-hydration-error'
: 'https://react.dev/link/hydration-mismatch'
),
source: 'error',
},
......
......@@ -13,6 +13,8 @@ import webdriver from 'next-webdriver'
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
const isReact18 = true
describe('Client Navigation', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixture'),
......@@ -1669,19 +1671,19 @@ describe.each([[false], [true]])(
expect(
Number(await browser.eval('window.__test_async_executions'))
).toBe(
strictNextHead
strictNextHead || isReact18
? 1
: // <meta name="next-head-count" /> is floated before <script />.
// head-manager thinks it needs t add these again resulting in another execution.
// head-manager thinks it needs to add these again resulting in another execution.
2
)
expect(
Number(await browser.eval('window.__test_defer_executions'))
).toBe(
strictNextHead
strictNextHead || isReact18
? 1
: // <meta name="next-head-count" /> is floated before <script defer />.
// head-manager thinks it needs t add these again resulting in another execution.
// head-manager thinks it needs to add these again resulting in another execution.
2
)
......@@ -1690,20 +1692,20 @@ describe.each([[false], [true]])(
expect(
Number(await browser.eval('window.__test_async_executions'))
).toBe(strictNextHead ? 1 : 2)
).toBe(strictNextHead || isReact18 ? 1 : 2)
expect(
Number(await browser.eval('window.__test_defer_executions'))
).toBe(strictNextHead ? 1 : 2)
).toBe(strictNextHead || isReact18 ? 1 : 2)
await browser.elementByCss('#toggleScript').click()
await waitFor(2000)
expect(
Number(await browser.eval('window.__test_async_executions'))
).toBe(strictNextHead ? 1 : 2)
).toBe(strictNextHead || isReact18 ? 1 : 2)
expect(
Number(await browser.eval('window.__test_defer_executions'))
).toBe(strictNextHead ? 1 : 2)
).toBe(strictNextHead || isReact18 ? 1 : 2)
} finally {
if (browser) {
await browser.close()
......
......@@ -609,7 +609,11 @@ describe.each([[false], [true]])(
const documentHeadElement =
'<meta name="keywords" content="document head test"/>'
expect(html).toContain(`<head>${nextHeadElement}${documentHeadElement}`)
// charset is not actually at the top.
// data-next-hide-fouc comes first
expect(html).toContain(
`</style></noscript>${nextHeadElement}${documentHeadElement}`
)
})
}
)
......@@ -486,8 +486,7 @@ describe('app dir - rsc basics', () => {
const bundledReactVersionPattern =
process.env.__NEXT_EXPERIMENTAL_PPR === 'true' ? '-experimental-' : '-rc-'
// TODO: (React 19) During Beta, bundled and installed version match.
it.skip('should not use bundled react for pages with app', async () => {
it('should not use bundled react for pages with app', async () => {
const ssrPaths = ['/pages-react', '/edge-pages-react']
const promises = ssrPaths.map(async (pathname) => {
const resPages$ = await next.render$(pathname)
......@@ -507,7 +506,6 @@ describe('app dir - rsc basics', () => {
const ssrAppReactVersions = [
await resApp$('#react').text(),
await resApp$('#react-dom').text(),
await resApp$('#react-dom-server').text(),
]
ssrAppReactVersions.forEach((version) =>
......
......@@ -8,7 +8,7 @@
},
"dependencies": {
"next": "canary",
"react": "19.0.0-rc-7771d3a7-20240827",
"react-dom": "19.0.0-rc-7771d3a7-20240827"
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
......@@ -8,8 +8,8 @@
},
"dependencies": {
"next": "canary",
"react": "19.0.0-rc-7771d3a7-20240827",
"react-dom": "19.0.0-rc-7771d3a7-20240827"
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18",
......
......@@ -3,6 +3,8 @@ import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import webdriver from 'next-webdriver'
const isReact18 = true
describe('prerender native module', () => {
let next: NextInstance
......@@ -70,7 +72,9 @@ describe('prerender native module', () => {
/webpack-runtime\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.js/,
isReact18
? /node_modules\/react\/cjs\/react\.production\.min\.js/
: /node_modules\/react\/cjs\/react\.production\.js/,
],
notTests: [],
},
......@@ -80,7 +84,9 @@ describe('prerender native module', () => {
/webpack-runtime\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.js/,
isReact18
? /node_modules\/react\/cjs\/react\.production\.min\.js/
: /node_modules\/react\/cjs\/react\.production\.js/,
/node_modules\/sqlite3\/.*?\.js/,
/node_modules\/sqlite3\/.*?\.node/,
/node_modules\/sqlite\/.*?\.js/,
......
......@@ -19,6 +19,8 @@ import {
import webdriver from 'next-webdriver'
import stripAnsi from 'strip-ansi'
const isReact18 = true
describe('Prerender', () => {
let next: NextInstance
......@@ -2062,7 +2064,9 @@ describe('Prerender', () => {
/webpack-runtime\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.js/,
isReact18
? /node_modules\/react\/cjs\/react\.production\.min\.js/
: /node_modules\/react\/cjs\/react\.production\.js/,
],
notTests: [],
},
......@@ -2073,7 +2077,9 @@ describe('Prerender', () => {
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.js/,
isReact18
? /node_modules\/react\/cjs\/react\.production\.min\.js/
: /node_modules\/react\/cjs\/react\.production\.js/,
/\/world.txt/,
],
notTests: [
......@@ -2088,7 +2094,9 @@ describe('Prerender', () => {
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.js/,
isReact18
? /node_modules\/react\/cjs\/react\.production\.min\.js/
: /node_modules\/react\/cjs\/react\.production\.js/,
/node_modules\/@firebase\/firestore\/.*?\.js/,
],
notTests: [/\/world.txt/],
......@@ -2109,7 +2117,7 @@ describe('Prerender', () => {
)
)
} catch (error) {
error.message += `\n\nFiles:\n${files.join('\n')}`
error.message += `\n\nPage: ${check.page}\nFiles:\n${files.join('\n')}`
throw error
}
......
......@@ -30,10 +30,6 @@ describe('AMP Usage', () => {
let output = ''
beforeAll(async () => {
await rename(
join(appDir, 'pages/custom-scripts.js'),
join(appDir, 'pages/custom-scripts.js.bak')
)
await rename(
join(appDir, 'pages/invalid-amp.js'),
join(appDir, 'pages/invalid-amp.js.bak')
......@@ -49,10 +45,6 @@ describe('AMP Usage', () => {
app = await nextStart(appDir, context.appPort)
})
afterAll(async () => {
await rename(
join(appDir, 'pages/custom-scripts.js.bak'),
join(appDir, 'pages/custom-scripts.js')
)
await rename(
join(appDir, 'pages/invalid-amp.js.bak'),
join(appDir, 'pages/invalid-amp.js')
......@@ -565,25 +557,6 @@ describe('AMP Usage', () => {
expect(inspectPayload).toContain('error')
})
it('should detect amp validator warning on custom scripts', async () => {
let inspectPayload = ''
dynamicAppPort = await findPort()
ampDynamic = await launchApp(join(__dirname, '../'), dynamicAppPort, {
onStdout(msg) {
inspectPayload += msg
},
onStderr(msg) {
inspectPayload += msg
},
})
await renderViaHTTP(dynamicAppPort, '/custom-scripts')
await killApp(ampDynamic)
expect(inspectPayload).toContain('error')
})
// eslint-disable-next-line jest/no-identical-title
it('should not contain missing files warning', async () => {
expect(output).toContain('Compiled /only-amp')
......
......@@ -15,6 +15,8 @@ const appDir = path.join(__dirname, '..')
let appPort
let app
const isReact18 = true
const runTests = () => {
it('Supports commonjs 1', async () => {
const browser = await webdriver(appPort, '/commonjs1')
......@@ -99,7 +101,19 @@ describe('Auto Export', () => {
expect.arrayContaining([
{
message: expect.stringContaining(
'https://react.dev/link/hydration-mismatch'
'See more info here: https://nextjs.org/docs/messages/react-hydration-error'
),
source: 'error',
},
])
)
expect(logs).toEqual(
expect.arrayContaining([
{
message: expect.stringContaining(
isReact18
? 'https://nextjs.org/docs/messages/react-hydration-error'
: 'https://react.dev/link/hydration-mismatch'
),
source: 'error',
},
......
export const metadata = {
title: 'Next.js',
description: 'Generated by Next.js',
}
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
import React from 'react'
async function CustomComponent() {
function CustomComponent() {
return (
<div>
<h1>the content of a dynamic component</h1>
......
......@@ -1180,7 +1180,7 @@ function runTests(mode) {
expect(warnings).toEqual([])
expect(await browser.elementById('img').getAttribute('src')).toBe(null)
expect(await browser.elementById('img').getAttribute('src')).toBe('')
expect(await browser.elementById('img').getAttribute('srcset')).toBe(null)
expect(await browser.elementById('img').getAttribute('width')).toBe('200')
expect(await browser.elementById('img').getAttribute('height')).toBe(
......@@ -1195,7 +1195,7 @@ function runTests(mode) {
)
expect(warnings).toEqual([])
expect(await browser.elementById('img').getAttribute('src')).toBe(null)
expect(await browser.elementById('img').getAttribute('src')).toBe('')
expect(await browser.elementById('img').getAttribute('srcset')).toBe(null)
expect(await browser.elementById('img').getAttribute('width')).toBe('200')
expect(await browser.elementById('img').getAttribute('height')).toBe(
......
......@@ -32,7 +32,7 @@ describe('Basics', () => {
const browser = await webdriver(context.appPort, '/')
expect(await browser.eval('window.didHydrate')).toBe(true)
expect(await browser.elementById('react-dom-version').text()).toMatch(
/19/
/18/
)
})
......
......@@ -49,9 +49,10 @@ type OmitFirstArgument<F> = F extends (
? (...args: P) => R
: never
// TODO: Base this off of test matrix
// Do not rename or format. sync-react script relies on this line.
// prettier-ignore
const nextjsReactPeerVersion = "19.0.0-rc-7771d3a7-20240827";
const nextjsReactPeerVersion = "^18.2.0";
export class NextInstance {
protected files: FileRef | { [filename: string]: string | FileRef }
......
......@@ -28,7 +28,7 @@ describe('custom server', () => {
it('should render pages with installed react', async () => {
const $ = await next.render$(`/2`)
expect($('body').text()).toMatch(/pages: 19.0.0/)
expect($('body').text()).toMatch(/pages: 18\.\d+\.\d+\{/)
})
})
})
......
......@@ -29,6 +29,8 @@ if (process.env.TEST_WASM) {
jest.setTimeout(120 * 1000)
}
const isReact18 = true
describe('Production Usage', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, '../fixture'),
......@@ -181,7 +183,9 @@ describe('Production Usage', () => {
/webpack-runtime\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.js/,
isReact18
? /node_modules\/react\/cjs\/react\.production\.min\.js/
: /node_modules\/react\/cjs\/react\.production\.js/,
],
notTests: [/\0/, /\?/, /!/],
},
......@@ -192,7 +196,9 @@ describe('Production Usage', () => {
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.js/,
isReact18
? /node_modules\/react\/cjs\/react\.production\.min\.js/
: /node_modules\/react\/cjs\/react\.production\.js/,
/node_modules\/next/,
],
notTests: [/\0/, /\?/, /!/],
......@@ -204,7 +210,9 @@ describe('Production Usage', () => {
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.js/,
isReact18
? /node_modules\/react\/cjs\/react\.production\.min\.js/
: /node_modules\/react\/cjs\/react\.production\.js/,
/node_modules\/next/,
/node_modules\/nanoid\/index\.js/,
/node_modules\/nanoid\/url-alphabet\/index\.js/,
......@@ -219,7 +227,9 @@ describe('Production Usage', () => {
/chunks\/.*?\.js/,
/node_modules\/react\/index\.js/,
/node_modules\/react\/package\.json/,
/node_modules\/react\/cjs\/react\.production\.js/,
isReact18
? /node_modules\/react\/cjs\/react\.production\.min\.js/
: /node_modules\/react\/cjs\/react\.production\.js/,
/node_modules\/next/,
],
notTests: [
......
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