EmotionCSSProp和Nextjs新的JSX运行时-错误:运行时自动时无法设置pragma和pragmaFrag
我正在尝试在 Nextjs 10.1 中使用 Emotion 11 的 CSS Prop 按照文档,我的 .babelrc 文件如下:
{
"presets": [
[
"next/babel",
{
"preset-react": {
"runtime": "automatic",
"importSource": "@emotion/react"
}
}
]
],
"plugins": ["@emotion/babel-plugin"]
}
我的 Nextjs 页面:
/** @jsx jsx */
import { css, jsx } from '@emotion/react'
export default function testPage() {
const color = 'darkgreen'
return (<div
css={css`
background-color: hotpink;
&:hover {
color: ${color};
}
`}
>
This has a hotpink background.
</div>)
}
我收到以下错误:
当运行时为自动时,不能设置 pragma 和 pragmaFrag。
如果我删除编译指示,/** @jsx jsx */我会在 HTML 代码中得到这个:
<div css="You have tried to stringify object returned from `css` function. It isn't supposed to be used directly (e.g. as value of the `className` prop), but rather handed to emotion so it can handle it (e.g. as value of `css` prop).">This has a hotpink background.</div>
这些是我的依赖项:
"dependencies": {
"@emotion/react": "^11.1.5",
"@emotion/babel-plugin": "^11.2.0",
"next": "^10.0.0",
"react": "17.0.1",
"react-dom": "17.0.1"
}
回答
解决它的最简单方法是替换/** @jsx jsx */by /** @jsxImportSource @emotion/react */,我什至不再需要导入 jsx:
/** @jsxImportSource @emotion/react */
import { css } from "@emotion/react"
export default function testPage() {
const color = 'darkgreen'
return (<div
css={css`
background-color: hotpink;
&:hover {
color: ${color};
}
`}
>
This has a hotpink background.
</div>)
}
THE END
二维码