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

Monorepo中用Vite构建React UI组件库遇JSX配置及解析错误

Monorepo下Vite构建React UI组件库的JSX配置错误排查

问题场景

在Monorepo环境开发React UI组件库,使用Vite构建ESM和CJS模块时触发以下错误:

Module './components/button.js' was resolved to '[...]/libs/ui/src/components/button.tsx', but '--jsx' is not set.

若移除react/jsx-runtime的外部依赖配置,会出现另一错误:

error during build:
[vite]: Rollup failed to resolve import "react/jsx-runtime" from "[...]/libs/ui/src/components/button.tsx".


相关代码片段

Button组件(src/components/button.tsx)

import React, { ComponentProps } from 'react'
import "../index.css";
 
export function Button(props: Omit<ComponentProps<'button'>, 'className'>) {
  return <button className="bg-blue-500 text-white px-4 py-2 rounded" {...props} />;
}

导出入口(src/main.ts)

export { Button } from './components/button.js';

Vite配置(vite.config.ts)

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import dts from 'vite-plugin-dts'
import path from 'path'
import packageJson from './package.json'

export default defineConfig({
  root: '/',
  plugins: [react(), dts({ include: 'src' })],
  build: {
    lib: {
      entry: path.resolve(__dirname, 'src/index.ts'),
      formats: ['es', 'cjs']
    },
    rollupOptions: {
      external: ['react', 'react-dom', 'react/jsx-runtime', 'tailwindcss']
    },
    sourcemap: true
  }
})

TypeScript配置(tsconfig.json)

{
  "extends": "../../tsconfig.json",
  "include": ["src/**/*.ts", "src/**/*.tsx"],
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "jsx": "react-jsx",
    "resolveJsonModule": true
  },
  "exclude": ["node_modules/"]
}

解决方案

1. 修正模块导入后缀

src/main.ts中用.js后缀导入.tsx文件,会导致TypeScript无法正确识别JSX文件类型。修改为以下两种方式之一:

// 方式一:使用tsx后缀
export { Button } from './components/button.tsx';

// 方式二:移除后缀(推荐,符合TS模块解析规则)
export { Button } from './components/button';

2. 调整Vite的root配置

当前root: '/'会导致Monorepo环境下路径解析混乱,改为当前包的根目录(或直接移除root配置,默认即为当前目录):

export default defineConfig({
  root: __dirname,
  // ...其他配置
})

3. 优化外部依赖配置

  • 确保项目React版本≥17(react/jsx-runtime为React 17+新增特性)
  • 在package.json中将react、react-dom设为peerDependencies,由用户项目提供依赖
  • 移除external中的react/jsx-runtime,Vite的react插件会自动处理该依赖的解析:
rollupOptions: {
  external: ['react', 'react-dom', 'tailwindcss']
}

4. 检查根目录tsconfig继承冲突

由于当前tsconfig继承了../../tsconfig.json,需确认根目录配置未覆盖jsx字段(比如根配置是否设置jsx: "none"),确保当前包的tsconfig.json中jsx: "react-jsx"生效。


验证步骤

  1. 保存所有配置修改
  2. 清理node_modules和dist目录
  3. 重新执行构建命令,确认错误消除

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 05:22:07