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

如何移除Vite+React+TS项目中每个文件的@jsxImportSource @emotion/react

解决Vite + React + TS + Emotion全局配置不生效问题

针对你遇到的全局配置后仍需在每个文件添加/** @jsxImportSource @emotion/react */指令的问题,下面是具体排查和解决步骤:

1. 确认依赖完整性

先确保所有必要的Emotion相关依赖已安装:

npm install @emotion/react @emotion/styled @emotion/babel-plugin
# 或使用yarn
yarn add @emotion/react @emotion/styled @emotion/babel-plugin

2. 修正tsconfig.json配置细节

检查tsconfig.json是否存在配置覆盖或缺失:

  • 确认jsx字段确实设置为react-jsx,且未被其他配置文件(如tsconfig.node.json)覆盖
  • 显式添加jsxRuntime字段明确指定自动运行时:
{
  "compilerOptions": {
    // ...其他原有配置
    "jsx": "react-jsx",
    "jsxRuntime": "automatic",
    "jsxImportSource": "@emotion/react",
    "types": ["vite-plugin-svgr/client"]
  }
}

3. 调整Vite插件配置

修改vite.config.ts,避免外部babel配置干扰,并确保插件参数正确:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [
    react({
      jsxImportSource: '@emotion/react',
      babel: {
        plugins: ['@emotion/babel-plugin'],
        babelrc: false,
        configFile: false,
      },
    }),
  ],
});

4. 清除缓存并重启服务

Vite缓存可能导致配置未生效,执行以下操作:

  • 停止当前Vite服务
  • 删除项目根目录下的node_modules/.vite文件夹
  • 重新启动服务:npm run dev

5. 升级TypeScript版本

旧版TypeScript对jsxImportSource的支持可能存在缺陷,建议升级到最新稳定版:

npm install typescript@latest --save-dev

6. 验证文件规范

确保所有使用Emotion的组件文件都是.tsx扩展名,且未在文件中使用React.createElement这类旧JSX语法,这类语法会绕过全局JSX配置。

如果以上步骤都无效,可以尝试搭建一个最小化的测试项目,逐步迁移配置和代码,排查是否是项目中其他依赖或自定义配置导致的冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:50:28