You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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转换:

  1. 安装依赖:
npm install @craco/craco @emotion/babel-plugin --save-dev
  1. 在项目根目录创建craco.config.js:
module.exports = {
  babel: {
    plugins: ["@emotion/babel-plugin"],
    presets: [
      [
        "@babel/preset-react",
        { runtime: "automatic", importSource: "@emotion/react" }
      ]
    ]
  }
};
  1. 修改package.json中的脚本命令,替换为craco:
"scripts": {
  "start": "craco start",
  "build": "craco build",
  "test": "craco test"
}
  1. 保持tsconfig.json中的jsx和jsxImportSource配置,无需再添加文件顶部的注释。

内容的提问来源于stack exchange,提问作者frankenapps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 02:24:12