Commit 6390a4ba authored by Benjamin Woodruff's avatar Benjamin Woodruff

Turbopack: Generate a warning if both react-compiler and styled-jsx are enabled,…

Turbopack: Generate a warning if both react-compiler and styled-jsx are enabled, suggest manually configuring them with babelrc
parent d0857f9d
......@@ -203,6 +203,42 @@ function warnCustomizedOption(
}
}
function warnReactCompilerStyledJsxIncompatibility(
config: NextConfig,
configFileName: string,
silent: boolean
) {
if (
!silent &&
config.compiler?.styledJsx &&
config.experimental?.reactCompiler
) {
Log.warnOnce(
'Due to an ordering incompatibility between SWC and Babel transformations, Next.js cannot ' +
'safely use both the built-in `styledJsx` and `reactCompiler` options. You should ' +
`disable both of these options in ${configFileName} and manually configure them as babel ` +
'plugins instead.\n' +
'\n' +
'See this page for how to configure babel: https://nextjs.org/docs/pages/guides/babel\n' +
'\n' +
'Details on configuring styled-jsx and React Compiler:\n' +
' \u2022 https://github.com/vercel/styled-jsx#getting-started\n' +
' \u2022 https://react.dev/reference/react-compiler/configuration\n' +
'\n' +
'You must configure the `styled-jsx/babel` plugin to run before ' +
'`babel-plugin-react-compiler`:\n' +
'\n' +
' // babel.config.js\n' +
' module.exports = {\n' +
' "plugins": ["styled-jsx/babel", "babel-plugin-react-compiler"],\n' +
' }\n' +
'\n' +
'The Babel implementation of styled-jsx may be slower and may have minor ' +
'incompabilities with the SWC version that Next.js uses by default.\n'
)
}
}
/**
* Assigns defaults to the user config and validates the config.
*
......@@ -1206,6 +1242,8 @@ function assignDefaultsAndValidate(
result.distDir = join(result.distDir, 'dev')
}
warnReactCompilerStyledJsxIncompatibility(result, configFileName, silent)
return result as NextConfigComplete
}
......
import StyledJsxRegistry from '../lib/registry'
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body>
<StyledJsxRegistry>{children}</StyledJsxRegistry>
</body>
</html>
)
}
'use client'
import { useEffect, useState } from 'react'
export default function Home() {
const [toggle, setToggle] = useState(false)
let $_: any
if (typeof window !== 'undefined') {
// eslint-disable-next-line no-eval
$_ = eval('typeof $ !== undefined ? $ : undefined')
}
useEffect(() => {
if (Array.isArray($_)) {
document.getElementById('react-compiler-enabled-message')!.textContent =
'React compiler is enabled'
}
})
return (
<>
<button className="hello" onClick={() => setToggle((dm) => !dm)}>
<p>Hello World</p>
<h1 id="react-compiler-enabled-message" />
</button>
<style jsx>{`
.hello {
background-color: ${toggle ? '#FF0000' : '#0000FF'};
}
`}</style>
</>
)
}
import { nextTestSetup, isNextDev, FileRef } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { join } from 'path'
import stripAnsi from 'strip-ansi'
function nextConfigFromJson(config) {
return `module.exports = ${JSON.stringify(config)}`
}
describe('react-compiler-with-styled-jsx', () => {
if (isNextDev) {
describe('config validation', () => {
const baseConfig = {
compiler: {
styledJsx: {
useLightningCss: true,
},
},
}
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'app')),
lib: new FileRef(join(__dirname, 'lib')),
'next.config.js': nextConfigFromJson(baseConfig),
},
dependencies: {
'babel-plugin-react-compiler': '19.1.0-rc.2',
},
})
it('warns about combining `reactCompiler` with `styledJsx`', async () => {
const warningSnippet =
'cannot safely use both the built-in `styledJsx` and `reactCompiler`'
expect(stripAnsi(next.cliOutput)).not.toContain(warningSnippet)
const outputIndex = next.cliOutput.length
const configWithReactCompiler = {
...baseConfig,
experimental: {
reactCompiler: true,
},
}
await next.patchFile(
'next.config.js',
nextConfigFromJson(configWithReactCompiler),
async () => {
await retry(async () => {
expect(stripAnsi(next.cliOutput.slice(outputIndex))).toContain(
warningSnippet
)
})
}
)
})
})
}
// this demonstrates the bug caused if you configure babel with the wrong plugin ordering
describe('incorrectly ordered manual babel config', () => {
const babelConfig = {
presets: ['next/babel'],
plugins: ['babel-plugin-react-compiler', 'styled-jsx/babel'],
}
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'app')),
lib: new FileRef(join(__dirname, 'lib')),
'next.config.js': nextConfigFromJson({}),
'.babelrc': JSON.stringify(babelConfig),
},
dependencies: {
'babel-plugin-react-compiler': '19.1.0-rc.2',
'styled-jsx': '5.1.7',
'babel-loader': '10.0.0',
},
})
it('fails to update style on button click', async () => {
const session = await next.browser('/')
const button = await session.elementByCss('.hello')
for (let i = 0; i < 5; i++) {
await button.click()
// the style never changes from the original value (blue)
expect(await button.getComputedCss('background-color')).toBe(
'rgb(0, 0, 255)'
)
}
})
})
describe.each([
['without react compiler', false, false],
['with styled-jsx in babelrc, but without react compiler', true, false],
['with babelrc and react compiler', true, true],
])('%s', (_name, hasBabelrc, hasReactCompiler) => {
const babelFiles = hasBabelrc
? {
'.babelrc': JSON.stringify({
presets: ['next/babel'],
plugins: [
'styled-jsx/babel',
// react compiler must run after the styled-jsx plugin
...(hasReactCompiler ? ['babel-plugin-react-compiler'] : []),
],
}),
}
: {}
const { next } = nextTestSetup({
files: {
app: new FileRef(join(__dirname, 'app')),
lib: new FileRef(join(__dirname, 'lib')),
'next.config.js': nextConfigFromJson(
hasBabelrc
? {} // the babelrc will configure styled-jsx
: {
compiler: {
styledJsx: {
useLightningCss: true,
},
},
}
),
...babelFiles,
},
dependencies: {
'babel-plugin-react-compiler': '19.1.0-rc.2',
'styled-jsx': '5.1.7',
'babel-loader': '10.0.0',
},
})
if (hasReactCompiler) {
it('applies the react compiler transform', async () => {
const session = await next.browser('/')
await retry(async () => {
const text = session
.elementByCss('#react-compiler-enabled-message')
.text()
expect(text).toMatch(/React compiler is enabled/)
})
})
}
it('updates style on state updates', async () => {
const session = await next.browser('/')
const button = await session.elementByCss('.hello')
// clicking on the button should change it from blue to red
expect(await button.getComputedCss('background-color')).toBe(
'rgb(0, 0, 255)'
)
await button.click()
expect(await button.getComputedCss('background-color')).toBe(
'rgb(255, 0, 0)'
)
})
})
})
"use client";
import React, { useState } from "react";
import { useServerInsertedHTML } from "next/navigation";
import { StyleRegistry, createStyleRegistry } from "styled-jsx";
export default function StyledJsxRegistry({
children,
}: {
children: React.ReactNode;
}) {
// Only create stylesheet once with lazy initial state
// x-ref: https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
const [jsxStyleRegistry] = useState(() => createStyleRegistry());
useServerInsertedHTML(() => {
const styles = jsxStyleRegistry.styles();
jsxStyleRegistry.flush();
return <>{styles}</>;
});
return <StyleRegistry registry={jsxStyleRegistry}>{children}</StyleRegistry>;
}
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