Turborepo中使用shadcn UI的Button组件报JSX组件错误求助
在Turborepo环境下,从自定义ui包引入Button组件,代码可正常运行,但TypeScript始终提示“'Button' cannot be used as a JSX component”错误。以下是相关代码及配置:
组件引入代码
import { Button } from 'ui'; export default function Page() { return ( <> <Button>test</Button> </> ); }
Next.js项目(apps/app)package.json配置
{ "name": "web", "version": "1.0.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint" }, "dependencies": { "next": "^13.4.1", "react": "^18.2.0", "react-dom": "^18.2.0", "ui": "workspace:*" }, "devDependencies": { "@total-typescript/ts-reset": "^0.4.2", "@types/node": "^17.0.12", "@types/react": "^18.0.22", "@types/react-dom": "^18.0.7", "autoprefixer": "^10.4.14", "eslint-config-custom": "workspace:*", "postcss": "^8.4.25", "tailwindcss": "^3.3.2", "tsconfig": "workspace:*", "typescript": "^4.5.3" } }
next.config.js配置
module.exports = { reactStrictMode: true, transpilePackages: ["ui"], };
可能的解决方法
1. 统一React及类型包版本
确保自定义ui包的package.json中,react、react-dom、@types/react、@types/react-dom的版本和Next.js项目完全一致。如果UI包将这些设为peerDependencies,要保证主项目安装的版本满足要求,避免UI包自身重复安装依赖。
2. 检查UI包TS配置与类型导出
- 确认UI包
tsconfig.json的compilerOptions.jsx设置为"react-jsx"(匹配React 18及Next.js的配置)。 - 确保UI包编译后生成正确的
.d.ts类型文件,且在package.json中通过types字段指定类型入口,比如:{ "types": "./dist/index.d.ts" }
3. 清理缓存并重启TS服务
- 执行
turbo clean清理Turborepo缓存 - 执行
next clean或删除.next文件夹清理Next.js缓存 - 重启编辑器的TypeScript服务(如VSCode中按
Ctrl+Shift+P选择"TypeScript: Restart TS Server")
4. 检查组件导出正确性
确保Button组件在UI包中正确导出,比如:
// ui包/components/Button.tsx import type { ReactNode } from 'react'; export const Button = ({ children }: { children: ReactNode }) => { return <button>{children}</button>; };
并在UI包入口文件(如index.ts)统一导出:
export { Button } from './components/Button';
5. 升级TypeScript版本
当前项目使用TypeScript 4.5.3,而Next.js 13.4.1推荐使用TypeScript 5.x版本,升级到^5.0.0可能解决类型兼容问题。
内容的提问来源于stack exchange,提问作者Ilyas Adiyasa
相关产品推荐
相关产品推荐

