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};
use anyhow::{Context, Result};
use regex::Regex;
use serde::Serialize;
use turbo_esregex::EsRegex;
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, Vc};
......@@ -16,7 +17,7 @@ use turbopack_core::{
use turbopack_node::transforms::webpack::WebpackLoaderItem;
use crate::{
next_config::{NextConfig, ReactCompilerCompilationMode},
next_config::{NextConfig, ReactCompilerCompilationMode, ReactCompilerOptions},
next_import_map::try_get_next_package,
next_shared::webpack_rules::{
ManuallyConfiguredBuiltinLoaderIssue, WebpackLoaderBuiltinCondition,
......@@ -145,15 +146,38 @@ pub async fn get_babel_loader_rules(
}
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) =
resolve_babel_plugin_react_compiler(next_config, project_path).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 =
serde_json::Value::Array(vec![serde_json::Value::Array(vec![
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"),
])]);
......
......@@ -155,7 +155,7 @@
"abort-controller": "3.0.0",
"alex": "9.1.0",
"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",
"buffer": "5.6.0",
"cheerio": "0.22.0",
......
......@@ -234,7 +234,7 @@
"async-sema": "3.0.0",
"axe-playwright": "2.0.3",
"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-react-remove-prop-types": "0.4.24",
"browserify-zlib": "0.2.0",
......
import type { EnvironmentConfig } from 'babel-plugin-react-compiler'
import path from 'path'
import type { JSONValue, ReactCompilerOptions } from '../server/config-shared'
import type { NextBabelLoaderOptions } from './babel/loader/types'
......@@ -23,16 +24,14 @@ const getReactCompilerPlugins = (
return undefined
}
const defaultOptions: ReactCompilerOptions = isDev
? {
// TODO: enable `environment.enableNameAnonymousFunctions`Ï
}
: {}
const environment: Pick<EnvironmentConfig, 'enableNameAnonymousFunctions'> = {
enableNameAnonymousFunctions: isDev,
}
const options: ReactCompilerOptions =
typeof maybeOptions === 'boolean' ? {} : maybeOptions
const compilerOptions: JSONValue = {
...defaultOptions,
...options,
environment,
}
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'
import { useEffect } from 'react'
import { Profiler, useReducer } from 'react'
export default function Page() {
let $_: any
if (typeof window !== 'undefined') {
// eslint-disable-next-line no-eval
$_ = eval('$')
}
if (typeof window !== 'undefined') {
;(window as any).staticChildRenders = 0
}
useEffect(() => {
if (Array.isArray($_)) {
document.getElementById('react-compiler-enabled-message')!.textContent =
`React compiler is enabled with ${$_!.length} memo slots`
}
})
function StaticChild() {
return (
<Profiler
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 (
<>
<div>
<h1 id="react-compiler-enabled-message" />
<p>hello world</p>
</div>
<div data-testid="parent-commits">Parent commits: {count}</div>
<button onClick={increment}>Increment</button>
<StaticChild />
</>
)
}
......@@ -5,6 +5,7 @@ const nextConfig = {
experimental: {
reactCompiler: true,
},
reactProductionProfiling: true,
}
module.exports = nextConfig
......@@ -16,88 +16,158 @@ function normalizeCodeLocInfo(str) {
)
}
describe.each(['default', 'babelrc'])('react-compiler %s', (variant) => {
const dependencies = (global as any).isNextDeploy
? // `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({
files:
variant === 'babelrc'
? __dirname
: {
app: new FileRef(join(__dirname, 'app')),
'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',
...dependencies,
},
})
it('should show an experimental warning', async () => {
await retry(() => {
expect(next.cliOutput).toContain('Experiments (use with caution)')
expect(stripAnsi(next.cliOutput)).toContain('✓ reactCompiler')
describe.each(['default', 'babelrc'] as const)(
'react-compiler %s',
(variant) => {
const dependencies = (global as any).isNextDeploy
? // `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, isTurbopack } = nextTestSetup({
files:
variant === 'babelrc'
? __dirname
: {
app: new FileRef(join(__dirname, 'app')),
'next.config.js': new FileRef(join(__dirname, 'next.config.js')),
'reference-library': new FileRef(
join(__dirname, 'reference-library')
),
},
// TODO: set only config instead once bundlers are consistent
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 render', async () => {
const browser = await next.browser('/')
it('should memoize Components', async () => {
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 () => {
const text = await browser
.elementByCss('#react-compiler-enabled-message')
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('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()
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('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/)
})
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 |'
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 |'
)
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