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

Vite+TypeScript集成Emotion.js时无法解析jsx-dev-runtime

解决方案

1. 移除干扰性插件

错误提示require is not defined源于vite-plugin-commonjs将ES模块强制转换为CommonJS格式,而浏览器环境不支持require语法。Vite本身已内置CommonJS模块支持,无需额外安装该插件。修改vite.config.ts:

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

export default defineConfig({
  plugins: [
    react({
      babel: {
        plugins: ["@emotion/babel-plugin"],
      },
    }),
  ],
  resolve: {
    alias: {
      src: "/src",
    },
  },
})

2. 确认依赖完整性

确保所有Emotion相关依赖都已正确安装:

yarn add @emotion/react @emotion/css
yarn add -D @emotion/babel-plugin

3. 优化TypeScript配置(可选)

为获得更完善的类型提示,在tsconfig.json的compilerOptions中添加@emotion/css类型声明:

{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "@emotion/react",
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
      "@/components/*": ["src/components/*"]
    },
    "types": ["@emotion/css"]
  },
  "files": [],
  "references": [
    { "path": "./tsconfig.app.json" },
    { "path": "./tsconfig.node.json" }
  ]
}

4. 验证代码写法

你的组件代码写法符合@emotion/css的规范,无需修改:

import React, { ReactNode } from 'react';
import { Layout } from 'antd';
import { Outlet } from 'react-router-dom';
import { css } from '@emotion/css';

interface BackgroundLayoutProps {
    children?: ReactNode
}

const BackgroundLayout: React.FC<BackgroundLayoutProps> = ({children}) => {
  return (
    <Layout className={css`background: black;`} style={{ height: "100vh"}}>
        {children}
        <Outlet />
    </Layout>
  );
};

export default BackgroundLayout;

5. 重启开发服务

停止当前运行的yarn dev进程,重新启动服务,确保所有配置修改生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 11:57:17