TypeScript+Create React App中Emotion CSS Prop样式不生效的原因
问题原因
在Create React App(CRA)的TypeScript项目中,直接修改tsconfig.json的jsxImportSource配置不会被CRA的编译流程识别——因为CRA会自行管理Babel和TypeScript的编译配置,导致Emotion的JSX转换逻辑未生效。此时css prop被当作普通字符串属性处理,触发了Emotion内置的提示信息。
解决方案
提供两种可行方案,按需选择:
方案1:文件级手动指定JSX导入源
在每个使用css prop的组件文件顶部添加注释,强制指定JSX的导入源为Emotion:
/** @jsxImportSource @emotion/react */ import { css } from "@emotion/react"; const myStyle = css({ backgroundColor: "red", display: "inline-block", height: 24, width: 24 }); export default function App() { return <div css={myStyle}></div>; }
方案2:通过Craco全局配置(推荐)
使用craco覆盖CRA的默认配置,全局启用Emotion的JSX转换:
- 安装依赖:
npm install @craco/craco @emotion/babel-plugin --save-dev
- 在项目根目录创建
craco.config.js:
module.exports = { babel: { plugins: ["@emotion/babel-plugin"], presets: [ [ "@babel/preset-react", { runtime: "automatic", importSource: "@emotion/react" } ] ] } };
- 修改
package.json中的脚本命令,替换为craco:
"scripts": { "start": "craco start", "build": "craco build", "test": "craco test" }
- 保持
tsconfig.json中的jsx和jsxImportSource配置,无需再添加文件顶部的注释。
内容的提问来源于stack exchange,提问作者frankenapps
相关产品推荐
相关产品推荐

