解决ShadCN CLI命令未找到问题
核心问题
执行 npx shadcn-ui add button
命令时报错 shadcn-ui: command not found
,即使重置环境或新建项目仍无法解决。
问题根源
ShadCN 官方近期(2024年下半年)对 CLI 工具进行了重大更新:
- CLI 工具名称从
shadcn-ui
改为shadcn
- 旧版命令语法已废弃且完全停止维护
- 官网文档已更新为新命令格式(未及时迁移的用户会遇到兼容问题)
✅ 正确解决方案
废弃命令
bash
npx shadcn-ui@latest add button # 已失效
步骤1:初始化项目(必需)
bash
npx shadcn@latest init
此命令将:
- 安装所有必要的依赖包
- 自动配置 Tailwind CSS
- 注入 CSS 变量到项目中
步骤2:添加组件
bash
npx shadcn@latest add button
完整工作流示例
bash
# 1. 创建新项目(以Next.js为例)
npm create next-app@latest
# 2. 进入项目目录
cd my-app
# 3. 初始化ShadCN配置
npx shadcn@latest init
# 4. 添加Button组件
npx shadcn@latest add button
特殊场景处理
在Monorepo中指定子目录:
bash
npx shadcn@latest add button -c ./apps/web
WSL环境额外步骤:
bash
# 先安装npm包
npm i shadcn-ui
# 解决依赖冲突
npm audit fix --force
# 再用新命令初始化
npx shadcn@latest init
⚠️ 错误做法
以下方案已被官方弃用:
bash
# 使用旧包名(无效)
npx shadcn-ui@0.8.0 add button
# 安装旧版全局包(不推荐)
npm install -g shadcn-ui
最佳实践建议
定期查阅官方文档
在API频繁更新期(如组件库v1.0前),每次使用前核对命令格式清除本地缓存
若升级后仍有问题,删除node_modules
和package-lock.json
后重新npm install
版本锁定策略
如需临时兼容旧项目,在命令中指定确切版本号:bashnpx shadcn@0.12.1 add button
遗留项目注意事项
现有使用 shadcn-ui
旧命令的项目需重新初始化:
- 备份组件代码
- 删除旧配置(如
components.json
) - 执行
npx shadcn init
重建
通过采用全新的
shadcn
CLI工具并遵循最新配置流程,可完全解决命令失效问题。遇到高严重性依赖冲突时,请结合使用npm audit fix --force
和最新ShadCN命令。