Unverified Commit 311eea4c authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Fix emotion-js transform for server components (#54284)

### What & Why

emotion-js has its own [jsx transform](https://emotion.sh/docs/typescript#emotionreact) which is being applied when `compiler.emotion` is enabled in `next.config.js`.

Thanks to emotion-js team that provided an emotion-js example setup with app router [here](https://github.com/emotion-js/emotion/issues/2928#issuecomment-1319792703), so that we can use it as test example with app router. Based on the setup, we create a test case working with emotion js but failed with error mentioned in #41994 that some client hooks appearing in server components. That is because the emotion-js jsx factory includes some client hooks.

### How

For server components, css-in-js is not recommended to apply so we disabled the transform before, the emotion jsx factory is a separate config that should also not be applied in server components. So in this case we still use react jsx factory instead of the emotion-js one for server components then it won't error. The test case can also be used as an example for basic emotion-js use case with app router.


Fixes #41994
Closes NEXT-1368
parent 76997cc0
...@@ -66,6 +66,8 @@ ...@@ -66,6 +66,8 @@
"@babel/preset-flow": "7.14.5", "@babel/preset-flow": "7.14.5",
"@babel/preset-react": "7.14.5", "@babel/preset-react": "7.14.5",
"@edge-runtime/jest-environment": "2.2.5", "@edge-runtime/jest-environment": "2.2.5",
"@emotion/cache": "11.11.0",
"@emotion/react": "11.11.1",
"@fullhuman/postcss-purgecss": "1.3.0", "@fullhuman/postcss-purgecss": "1.3.0",
"@mdx-js/loader": "2.2.1", "@mdx-js/loader": "2.2.1",
"@mdx-js/react": "2.2.1", "@mdx-js/react": "2.2.1",
......
...@@ -105,7 +105,9 @@ function getBaseSWCOptions({ ...@@ -105,7 +105,9 @@ function getBaseSWCOptions({
react: { react: {
importSource: importSource:
jsConfig?.compilerOptions?.jsxImportSource ?? jsConfig?.compilerOptions?.jsxImportSource ??
(compilerOptions?.emotion ? '@emotion/react' : 'react'), (compilerOptions?.emotion && !isServerLayer
? '@emotion/react'
: 'react'),
runtime: 'automatic', runtime: 'automatic',
pragma: 'React.createElement', pragma: 'React.createElement',
pragmaFrag: 'React.Fragment', pragmaFrag: 'React.Fragment',
......
This diff is collapsed.
'use client'
import { CacheProvider } from '@emotion/react'
import createCache from '@emotion/cache'
import { useServerInsertedHTML } from 'next/navigation'
import { useState } from 'react'
export default function RootStyleRegistry({ children }) {
const [{ cache, flush }] = useState(() => {
const cache = createCache({ key: 'emotion-cache' })
cache.compat = true
const prevInsert = cache.insert
let inserted = []
cache.insert = (...args) => {
const serialized = args[1]
if (cache.inserted[serialized.name] === undefined) {
inserted.push(serialized.name)
}
return prevInsert(...args)
}
const flush = () => {
const prevInserted = inserted
inserted = []
return prevInserted
}
return { cache, flush }
})
useServerInsertedHTML(() => {
const names = flush()
if (names.length === 0) return null
let styles = ''
for (const name of names) {
styles += cache.inserted[name]
}
return (
<style
data-emotion={`${cache.key} ${names.join(' ')}`}
dangerouslySetInnerHTML={{
__html: styles,
}}
/>
)
})
return <CacheProvider value={cache}>{children}</CacheProvider>
}
import EmotionRootStyleRegistry from './emotion-root-style-registry'
export default function RootLayout({ children }) {
return (
<html>
<head></head>
<body>
<EmotionRootStyleRegistry>{children}</EmotionRootStyleRegistry>
</body>
</html>
)
}
'use client'
export default function Page() {
return <h1 css={{ color: 'blue' }}>Blue</h1>
}
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app dir - emotion-js',
{
files: __dirname,
skipDeployment: true,
dependencies: {
'@emotion/react': 'latest',
'@emotion/cache': 'latest',
},
},
({ next }) => {
it('should render emotion-js css with compiler.emotion option correctly', async () => {
const browser = await next.browser('/')
const el = browser.elementByCss('h1')
expect(await el.text()).toBe('Blue')
await check(
async () =>
await browser.eval(
`window.getComputedStyle(document.querySelector('h1')).color`
),
'rgb(0, 0, 255)'
)
})
}
)
/** @type {import("next").NextConfig} */
module.exports = {
reactStrictMode: true,
compiler: {
emotion: true,
},
}
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