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

React TypeScript项目中Vite4配置Emotion js的问题排查

问题概述

将React TypeScript项目从Webpack迁移到Vite时,配置Emotion JS遇到以下问题:

  • 执行npm start后编译成功,但出现Vite警告:The JSX factory cannot be set when using React's "automatic" JSX transform
  • React组件中出现TS错误:'jsx' is declared but its value is never read.ts(6133)

当前依赖版本:

"@vitejs/plugin-react": "^4.0.1",
"vite": "^4.3.9",
"@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0"

已完成的配置步骤:

  1. 在.eslintrc.cjs中添加规则:
    "rules": { "react/no-unknown-property": ['error', { ignore: ['css'] }] }
    
  2. 在tsconfig.json中添加:
    "types": ["vite-plugin-svgr/client", "@emotion/react/types/css-prop"]
    
  3. 在vite.config.ts中配置:
    export default defineConfig({ plugins: [ react({ jsxImportSource: '@emotion/react', }), ] })
    

涉及的组件代码:

/** @jsx jsx */
import { jsx, useTheme } from '@emotion/react';
import { Link } from 'react-router-dom';

import { RTLLogo } from 'app/components/atoms/icons';
import { HomePage } from 'app/routes/paths';

import Styles from './Logo.styles';
import { Props } from './Logo.types';

const MyComponent = ({ classes }: Props) => {
  const theme = useTheme();
  const styles = Styles({ theme, classes });

  return (
    <Link to={HomePage} css={styles.root}>
      <Logo />
    </Link>
  );
};

export default MyComponent;
解决方案

1. 解决Vite警告与TS未使用变量错误

问题根源:同时使用了手动JSX工厂指令/** @jsx jsx */和Vite自动JSX转换配置jsxImportSource,两者冲突。

修改组件代码:

  • 移除顶部的/** @jsx jsx */注释
  • 移除import { jsx, useTheme }中的jsx导入

修改后的组件代码:

import { useTheme } from '@emotion/react';
import { Link } from 'react-router-dom';

import { RTLLogo } from 'app/components/atoms/icons';
import { HomePage } from 'app/routes/paths';

import Styles from './Logo.styles';
import { Props } from './Logo.types';

const MyComponent = ({ classes }: Props) => {
  const theme = useTheme();
  const styles = Styles({ theme, classes });

  return (
    <Link to={HomePage} css={styles.root}>
      <RTLLogo />
    </Link>
  );
};

export default MyComponent;

2. 确认关键配置正确性

  • vite.config.ts:确保jsxImportSource配置完整

    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [
        react({
          jsxImportSource: '@emotion/react',
        }),
      ],
    });
    
  • tsconfig.json:确保启用React自动JSX转换,添加jsx配置

    {
      "compilerOptions": {
        // 其他原有配置
        "jsx": "react-jsx", // 开发环境可使用react-jsxdev
        "types": ["vite-plugin-svgr/client", "@emotion/react/types/css-prop"]
      }
    }
    

3. 验证配置

重新执行npm start,Vite警告和TS错误应全部消失,Emotion的css prop可正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 02:17:24