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

Enable anonymous function naming in React Compiler (#84070)

Co-authored-by: 's avatarBenjamin Woodruff <benjamin.woodruff@vercel.com>
parent 55f83e0f
...@@ -2,6 +2,7 @@ use std::{collections::BTreeSet, sync::LazyLock}; ...@@ -2,6 +2,7 @@ use std::{collections::BTreeSet, sync::LazyLock};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use regex::Regex; use regex::Regex;
use serde::Serialize;
use turbo_esregex::EsRegex; use turbo_esregex::EsRegex;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc}; use turbo_tasks::{ResolvedVc, Vc};
...@@ -16,7 +17,7 @@ use turbopack_core::{ ...@@ -16,7 +17,7 @@ use turbopack_core::{
use turbopack_node::transforms::webpack::WebpackLoaderItem; use turbopack_node::transforms::webpack::WebpackLoaderItem;
use crate::{ use crate::{
next_config::{NextConfig, ReactCompilerCompilationMode}, next_config::{NextConfig, ReactCompilerCompilationMode, ReactCompilerOptions},
next_import_map::try_get_next_package, next_import_map::try_get_next_package,
next_shared::webpack_rules::{ next_shared::webpack_rules::{
ManuallyConfiguredBuiltinLoaderIssue, WebpackLoaderBuiltinCondition, ManuallyConfiguredBuiltinLoaderIssue, WebpackLoaderBuiltinCondition,
...@@ -145,15 +146,38 @@ pub async fn get_babel_loader_rules( ...@@ -145,15 +146,38 @@ pub async fn get_babel_loader_rules(
} }
let mut loader_conditions = Vec::new(); let mut loader_conditions = Vec::new();
if let Some(react_compiler_options) = &*react_compiler_options if let Some(react_compiler_options) = react_compiler_options.as_ref()
&& let Some(babel_plugin_path) = && let Some(babel_plugin_path) =
resolve_babel_plugin_react_compiler(next_config, project_path).await? resolve_babel_plugin_react_compiler(next_config, project_path).await?
{ {
let react_compiler_options = react_compiler_options.await?; let react_compiler_options = react_compiler_options.await?;
// we don't want to accept user-supplied `environment` options, but we do want to pass
// `enableNameAnonymousFunctions` down to the babel plugin based on dev/prod.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct EnvironmentOptions {
enable_name_anonymous_functions: bool,
}
#[derive(Serialize)]
struct ResolvedOptions<'a> {
#[serde(flatten)]
base: &'a ReactCompilerOptions,
environment: EnvironmentOptions,
}
let resolved_options = ResolvedOptions {
base: &react_compiler_options,
environment: EnvironmentOptions {
enable_name_anonymous_functions: builtin_conditions
.contains(&WebpackLoaderBuiltinCondition::Development),
},
};
let react_compiler_plugins = let react_compiler_plugins =
serde_json::Value::Array(vec![serde_json::Value::Array(vec![ serde_json::Value::Array(vec![serde_json::Value::Array(vec![
serde_json::Value::String(babel_plugin_path.into_owned()), serde_json::Value::String(babel_plugin_path.into_owned()),
serde_json::to_value(&*react_compiler_options) serde_json::to_value(resolved_options)
.expect("react compiler options JSON serialization should never fail"), .expect("react compiler options JSON serialization should never fail"),
])]); ])]);
......
...@@ -155,7 +155,7 @@ ...@@ -155,7 +155,7 @@
"abort-controller": "3.0.0", "abort-controller": "3.0.0",
"alex": "9.1.0", "alex": "9.1.0",
"async-sema": "3.0.1", "async-sema": "3.0.1",
"babel-plugin-react-compiler": "19.1.0-rc.2", "babel-plugin-react-compiler": "0.0.0-experimental-3fde738-20250918",
"browserslist": "4.25.1", "browserslist": "4.25.1",
"buffer": "5.6.0", "buffer": "5.6.0",
"cheerio": "0.22.0", "cheerio": "0.22.0",
......
...@@ -234,7 +234,7 @@ ...@@ -234,7 +234,7 @@
"async-sema": "3.0.0", "async-sema": "3.0.0",
"axe-playwright": "2.0.3", "axe-playwright": "2.0.3",
"babel-loader": "10.0.0", "babel-loader": "10.0.0",
"babel-plugin-react-compiler": "19.1.0-rc.2", "babel-plugin-react-compiler": "0.0.0-experimental-3fde738-20250918",
"babel-plugin-transform-define": "2.0.0", "babel-plugin-transform-define": "2.0.0",
"babel-plugin-transform-react-remove-prop-types": "0.4.24", "babel-plugin-transform-react-remove-prop-types": "0.4.24",
"browserify-zlib": "0.2.0", "browserify-zlib": "0.2.0",
......
import type { EnvironmentConfig } from 'babel-plugin-react-compiler'
import path from 'path' import path from 'path'
import type { JSONValue, ReactCompilerOptions } from '../server/config-shared' import type { JSONValue, ReactCompilerOptions } from '../server/config-shared'
import type { NextBabelLoaderOptions } from './babel/loader/types' import type { NextBabelLoaderOptions } from './babel/loader/types'
...@@ -23,16 +24,14 @@ const getReactCompilerPlugins = ( ...@@ -23,16 +24,14 @@ const getReactCompilerPlugins = (
return undefined return undefined
} }
const defaultOptions: ReactCompilerOptions = isDev const environment: Pick<EnvironmentConfig, 'enableNameAnonymousFunctions'> = {
? { enableNameAnonymousFunctions: isDev,
// TODO: enable `environment.enableNameAnonymousFunctions`Ï }
}
: {}
const options: ReactCompilerOptions = const options: ReactCompilerOptions =
typeof maybeOptions === 'boolean' ? {} : maybeOptions typeof maybeOptions === 'boolean' ? {} : maybeOptions
const compilerOptions: JSONValue = { const compilerOptions: JSONValue = {
...defaultOptions,
...options, ...options,
environment,
} }
return [[getReactCompiler(), compilerOptions]] return [[getReactCompiler(), compilerOptions]]
} }
......
This diff is collapsed.
'use client'
import { useEffect, useState } from 'react'
export default function Page() {
const [callFrame, setCallFrame] = useState(null)
useEffect(() => {
const error = new Error('test-top-frame')
console.error(error)
const callStack = new Error('test-top-frame').stack.split(
'test-top-frame\n'
)[1]
// indices might change due to different compiler optimizations
const callFrame = callStack.split('\n')[0]
setCallFrame(callFrame)
}, [])
return (
<pre data-testid="call-frame" aria-busy={callFrame === null}>
{String(callFrame)}
</pre>
)
}
'use client' 'use client'
import { useEffect } from 'react' import { Profiler, useReducer } from 'react'
export default function Page() { if (typeof window !== 'undefined') {
let $_: any ;(window as any).staticChildRenders = 0
if (typeof window !== 'undefined') { }
// eslint-disable-next-line no-eval
$_ = eval('$')
}
useEffect(() => { function StaticChild() {
if (Array.isArray($_)) { return (
document.getElementById('react-compiler-enabled-message')!.textContent = <Profiler
`React compiler is enabled with ${$_!.length} memo slots` onRender={(id, phase) => {
} ;(window as any).staticChildRenders += 1
}) }}
id="test"
>
<div>static child</div>
</Profiler>
)
}
export default function Page() {
const [count, increment] = useReducer((n) => n + 1, 1)
return ( return (
<> <>
<div> <div data-testid="parent-commits">Parent commits: {count}</div>
<h1 id="react-compiler-enabled-message" /> <button onClick={increment}>Increment</button>
<p>hello world</p> <StaticChild />
</div>
</> </>
) )
} }
...@@ -5,6 +5,7 @@ const nextConfig = { ...@@ -5,6 +5,7 @@ const nextConfig = {
experimental: { experimental: {
reactCompiler: true, reactCompiler: true,
}, },
reactProductionProfiling: true,
} }
module.exports = nextConfig module.exports = nextConfig
...@@ -16,88 +16,158 @@ function normalizeCodeLocInfo(str) { ...@@ -16,88 +16,158 @@ function normalizeCodeLocInfo(str) {
) )
} }
describe.each(['default', 'babelrc'])('react-compiler %s', (variant) => { describe.each(['default', 'babelrc'] as const)(
const dependencies = (global as any).isNextDeploy 'react-compiler %s',
? // `link` is incompatible with the npm version used when this test is deployed (variant) => {
{ const dependencies = (global as any).isNextDeploy
'reference-library': 'file:./reference-library', ? // `link` is incompatible with the npm version used when this test is deployed
} {
: { 'reference-library': 'file:./reference-library',
'reference-library': 'link:./reference-library', }
} : {
const { next, isNextDev } = nextTestSetup({ 'reference-library': 'link:./reference-library',
files: }
variant === 'babelrc' const { next, isNextDev, isTurbopack } = nextTestSetup({
? __dirname files:
: { variant === 'babelrc'
app: new FileRef(join(__dirname, 'app')), ? __dirname
'next.config.js': new FileRef(join(__dirname, 'next.config.js')), : {
'reference-library': new FileRef( app: new FileRef(join(__dirname, 'app')),
join(__dirname, 'reference-library') 'next.config.js': new FileRef(join(__dirname, 'next.config.js')),
), 'reference-library': new FileRef(
}, join(__dirname, 'reference-library')
),
dependencies: { },
'babel-plugin-react-compiler': '19.1.0-rc.2', // TODO: set only config instead once bundlers are consistent
...dependencies, buildArgs: ['--profile'],
}, dependencies: {
}) 'babel-plugin-react-compiler': '0.0.0-experimental-3fde738-20250918',
...dependencies,
it('should show an experimental warning', async () => { },
await retry(() => { })
expect(next.cliOutput).toContain('Experiments (use with caution)')
expect(stripAnsi(next.cliOutput)).toContain('✓ reactCompiler') it('should show an experimental warning', async () => {
await retry(() => {
expect(next.cliOutput).toContain('Experiments (use with caution)')
expect(stripAnsi(next.cliOutput)).toContain('✓ reactCompiler')
})
}) })
})
it('should render', async () => { it('should memoize Components', async () => {
const browser = await next.browser('/') const browser = await next.browser('/')
expect(await browser.eval('window.staticChildRenders')).toEqual(1)
expect(
await browser.elementByCss('[data-testid="parent-commits"]').text()
).toEqual('Parent commits: 1')
await browser.elementByCss('button').click()
await browser.elementByCss('button').click()
await browser.elementByCss('button').click()
expect(await browser.eval('window.staticChildRenders')).toEqual(1)
expect(
await browser.elementByCss('[data-testid="parent-commits"]').text()
).toEqual('Parent commits: 4')
})
it('should work with a library that uses the react-server condition', async () => {
const outputIndex = next.cliOutput.length
await next.render('/library-react-server')
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).not.toMatch(/error/)
})
await retry(async () => { it('should work with a library using use client', async () => {
const text = await browser const outputIndex = next.cliOutput.length
.elementByCss('#react-compiler-enabled-message') await next.render('/library-client')
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).not.toMatch(/error/)
})
it('should name functions in dev', async () => {
const browser = await next.browser('/function-naming')
await browser.waitForElementByCss(
'[data-testid="call-frame"][aria-busy="false"]',
5000
)
const callFrame = await browser
.elementByCss('[data-testid="call-frame"]')
.text() .text()
expect(text).toMatch(/React compiler is enabled with \d+ memo slots/) const devFunctionName =
variant === 'babelrc' && !isTurbopack
? // next/babel transpiles away arrow functions defeating the React Compiler naming
// TODO: Does Webpack or Turbopack get the Babel config right?
'PageUseEffect'
: // expected naming heuristic from React Compiler. This may change in future.
// Just make sure this is the heuristic from the React Compiler not something else.
'Page[useEffect()]'
if (isNextDev) {
if (isTurbopack) {
// FIXME: https://linear.app/vercel/issue/NAR-351
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "test-top-frame",
"environmentLabel": null,
"label": "Console Error",
"source": null,
"stack": [
"<FIXME-file-protocol>",
],
}
`)
} else {
await expect(browser).toDisplayCollapsedRedbox(`
{
"description": "test-top-frame",
"environmentLabel": null,
"label": "Console Error",
"source": "app/function-naming/page.tsx (8:19) @ ${devFunctionName}
> 8 | const error = new Error('test-top-frame')
| ^",
"stack": [
"${devFunctionName} app/function-naming/page.tsx (8:19)",
],
}
`)
}
// We care more about the sourcemapped frame in the Redbox.
// This assertion is only here to show that the negative assertion below is valid.
expect(normalizeCodeLocInfo(callFrame)).toEqual(
` at ${devFunctionName} (**)`
)
} else {
expect(normalizeCodeLocInfo(callFrame)).not.toEqual(
` at ${devFunctionName} (**)`
)
}
}) })
})
it('throws if the React Compiler is used in a React Server environment', async () => {
it('should work with a library that uses the react-server condition', async () => { const outputIndex = next.cliOutput.length
const outputIndex = next.cliOutput.length const browser = await next.browser('/library-missing-react-server')
await next.render('/library-react-server')
const cliOutput = normalizeCodeLocInfo(
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex)) stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).not.toMatch(/error/)
})
it('should work with a library using use client', async () => {
const outputIndex = next.cliOutput.length
await next.render('/library-client')
const cliOutput = stripAnsi(next.cliOutput.slice(outputIndex))
expect(cliOutput).not.toMatch(/error/)
})
it('throws if the React Compiler is used in a React Server environment', async () => {
const outputIndex = next.cliOutput.length
const browser = await next.browser('/library-missing-react-server')
const cliOutput = normalizeCodeLocInfo(
stripAnsi(next.cliOutput.slice(outputIndex))
)
if (isNextDev) {
// TODO(NDX-663): Unhelpful error message.
// Should say that the library should have a react-server entrypoint that doesn't use the React Compiler.
expect(cliOutput).toContain(
'' +
"\n ⨯ TypeError: Cannot read properties of undefined (reading 'H')" +
// location not important. Just that this is the only frame.
// TODO: Stack should start at product code. Possible React limitation.
'\n at Container (**)' +
// Will just point to original file location
'\n 2 |'
) )
if (isNextDev) {
// TODO(NDX-663): Unhelpful error message.
// Should say that the library should have a react-server entrypoint that doesn't use the React Compiler.
expect(cliOutput).toContain(
'' +
"\n ⨯ TypeError: Cannot read properties of undefined (reading 'H')" +
// location not important. Just that this is the only frame.
// TODO: Stack should start at product code. Possible React limitation.
'\n at Container (**)' +
// Will just point to original file location
'\n 2 |'
)
await assertHasRedbox(browser) await assertHasRedbox(browser)
} }
}) })
}) }
)
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