| name | shadcn |
| description | Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI, including chat interfaces. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset". |
| user-invocable | false |
| allowed-tools | Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *) |
shadcn/ui
一个用于构建 UI、组件和设计系统的框架。组件通过 CLI 以源代码形式添加到用户的项目中。
重要: 使用项目的包管理器运行所有 CLI 命令:npx shadcn@latest、pnpm dlx shadcn@latest 或 bunx --bun shadcn@latest — 基于项目的 packageManager。下面的示例使用 npx shadcn@latest,但请为项目替换正确的运行器。
当前项目上下文
!`npx shadcn@latest info --json`
上面的 JSON 包含项目配置和已安装的组件。使用 npx shadcn@latest docs <component> 获取任意组件的文档和示例 URL。
原则
- 优先使用现有组件。 在编写自定义 UI 之前,使用
npx shadcn@latest search 检查注册表。也要检查社区注册表。
- 组合,不要重复发明。 设置页面 = 标签页 + 卡片 + 表单控件。仪表板 = 侧边栏 + 卡片 + 图表 + 表格。
- 优先使用内置变体而非自定义样式。
variant="outline"、size="sm" 等。
- 使用语义化颜色。
bg-primary、text-muted-foreground — 永远不要使用原始值如 bg-blue-500。
关键规则
这些规则始终执行。每个都链接到包含错误/正确代码对的文件。
className 用于布局,而非样式。 永远不要覆盖组件颜色或排版。
- 不要使用
space-x-* 或 space-y-*。 使用 flex 配合 gap-*。对于垂直堆叠,使用 flex flex-col gap-*。
- 当宽度和高度相等时使用
size-*。 size-10 而不是 w-10 h-10。
- 使用
truncate 简写。 不要写 overflow-hidden text-ellipsis whitespace-nowrap。
- 不要手动覆盖
dark: 颜色。 使用语义化标记(bg-background、text-muted-foreground)。
- 使用
cn() 进行条件类名处理。 不要写手动模板字面量三元表达式。
- 不要在遮罩层组件上手动设置
z-index。 对话框、工作表、弹出框等自行处理堆叠。
- 表单使用
FieldGroup + Field。 永远不要用原始 div 配合 space-y-* 或 grid gap-* 进行表单布局。
InputGroup 使用 InputGroupInput/InputGroupTextarea。 永远不要在 InputGroup 内使用原始 Input/Textarea。
- 输入框内的按钮使用
InputGroup + InputGroupAddon。
- 选项组(2-7 个选择)使用
ToggleGroup。 不要用手动激活状态循环 Button。
- 相关复选框/单选按钮使用
FieldSet + FieldLegend 进行分组。 不要使用带标题的 div。
- 字段验证使用
data-invalid + aria-invalid。 data-invalid 在 Field 上,aria-invalid 在控件上。对于禁用状态:data-disabled 在 Field 上,disabled 在控件上。
- 项目始终在其组内。
SelectItem → SelectGroup。DropdownMenuItem → DropdownMenuGroup。CommandItem → CommandGroup。
- 使用
asChild (radix) 或 render (base) 自定义触发器。 从 npx shadcn@latest info 检查 base 字段。→ base-vs-radix.md
- 对话框、工作表和抽屉始终需要标题。
DialogTitle、SheetTitle、DrawerTitle 为可访问性所必需。如果视觉隐藏,使用 className="sr-only"。
- 使用完整的卡片组合。
CardHeader/CardTitle/CardDescription/CardContent/CardFooter。不要把所有内容都堆在 CardContent 里。
- 按钮没有
isPending/isLoading。 与 Spinner + data-icon + disabled 组合使用。
TabsTrigger 必须位于 TabsList 内。 永远不要直接在 Tabs 中渲染触发器。
Avatar 始终需要 AvatarFallback。 用于图片加载失败时。
- 优先使用现有组件而非自定义标记。 在编写样式化的
div 之前检查组件是否存在。
- 提示使用
Alert。 不要构建自定义样式化的 div。
- 空状态使用
Empty。 不要构建自定义空状态标记。
- 通过
sonner 使用 Toast。 使用 sonner 中的 toast()。
- 使用
Separator 代替 <hr> 或 <div className="border-t">。
- 使用
Skeleton 作为加载占位符。不要使用自定义的 animate-pulse div。
- 使用
Badge 代替自定义样式化的 span。
- Icons in
Button use data-icon. data-icon="inline-start" or data-icon="inline-end" on the icon.
- No sizing classes on icons inside components. Components handle icon sizing via CSS. No
size-4 or w-4 h-4.
- Pass icons as objects, not string keys.
icon={CheckIcon}, not a string lookup.
Chat & Messaging → chat.md
- Chat UI composes the chat primitives. Conversations use
MessageScroller, rows use Message, surfaces use Bubble. Never hand-rolled bubble divs or a raw scroll container.
MessageScroller owns scroll behavior. Streaming follow, anchoring, and jump-to-latest (MessageScrollerButton) are built in. Don't write a useStickToBottom/ResizeObserver hook.
- Attachments use
Attachment; system notes and dividers use Marker. Not Item cards or Separator + a label.
CLI
- Never decode preset codes or build preset URLs manually. Use
npx shadcn@latest preset decode <code>, preset url <code>, or preset open <code>. For project-aware preset detection, use npx shadcn@latest preset resolve.
- Apply preset codes directly with the CLI. Use
npx shadcn@latest apply <code> for existing projects, or npx shadcn@latest init --preset <code> when initializing.
关键模式
这些是与正确 shadcn/ui 代码区别最大的最常见模式。对于边缘情况,参见上面链接的规则文件。
<FieldGroup>
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input id="email" />
</Field>
</FieldGroup>
<Field data-invalid>
<FieldLabel>Email</FieldLabel>
<Input aria-invalid />
<FieldDescription>Invalid email.</FieldDescription>
</Field>
<Button>
<SearchIcon data-icon="inline-start" />
Search
</Button>
<div className="flex flex-col gap-4"> // 正确
<div className="space-y-4"> // 错误
// 等尺寸:size-*,而非 w-* h-*。
<Avatar className="size-10"> // 正确
<Avatar className="w-10 h-10"> // 错误
// 状态颜色:Badge 变体或语义化标记,而非原始颜色。
<Badge variant="secondary">+20.1%</Badge> // 正确
<span className="text-emerald-600">+20.1%</span> // 错误
组件选择
| 需求 | 使用 |
|---|
| Button/action | Button with appropriate variant |
| Form inputs | Input, Select, Combobox, Switch, Checkbox, RadioGroup, Textarea, InputOTP, Slider |
| Toggle between 2–5 options | ToggleGroup + ToggleGroupItem |
| Data display | Table, Card, Badge, Avatar |
| Navigation | Sidebar, NavigationMenu, Breadcrumb, Tabs, Pagination |
| Overlays | Dialog (modal), Sheet (side panel), Drawer (bottom sheet), AlertDialog (confirmation) |
| Feedback | sonner (toast), Alert, Progress, Skeleton, Spinner |
| Command palette | Command inside Dialog |
| Charts | Chart (wraps Recharts) |
| Layout | Card, Separator, Resizable, ScrollArea, Accordion, Collapsible |
| Empty states | Empty |
| Menus | DropdownMenu, ContextMenu, Menubar |
| Tooltips/info | Tooltip, HoverCard, Popover |
| Chat / conversation UI | MessageScroller, Message, Bubble, Attachment, Marker |
Key Fields
The injected project context contains these key fields:
aliases → use the actual alias prefix for imports (e.g. @/, ~/), never hardcode.
isRSC → when true, components using useState, useEffect, event handlers, or browser APIs need "use client" at the top of the file. Always reference this field when advising on the directive.
tailwindVersion → "v4" uses @theme inline blocks; "v3" uses tailwind.config.js.
tailwindCssFile → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.
style → component visual treatment (e.g. nova, vega).
base → primitive library (radix or base). Affects component APIs and available props.
iconLibrary → determines icon imports. Use lucide-react for lucide, @tabler/icons-react for tabler, etc. Never assume lucide-react.
resolvedPaths → exact file-system destinations for components, utils, hooks, etc.
framework → routing and file conventions (e.g. Next.js App Router vs Vite SPA).
packageManager → use this for any non-shadcn dependency installs (e.g. pnpm add date-fns vs npm install date-fns).
preset → resolved preset code and values for the current project. Use npx shadcn@latest preset resolve --json when you only need preset information.
See cli.md — info command for the full field reference.
Component Docs, Examples, and Usage
Run npx shadcn@latest docs <component> to get the URLs for a component's documentation, examples, and API reference. Fetch these URLs to get the actual content.
npx shadcn@latest docs button dialog select
在创建、修复、调试或使用组件时,始终先运行 npx shadcn@latest docs 并获取 URL。 这确保你使用的是正确的 API 和用法模式,而不是猜测。
工作流
- Get project context — already injected above. Run
npx shadcn@latest info again if you need to refresh.
- Check installed components first — before running
add, always check the components list from project context or list the resolvedPaths.ui directory. Don't import components that haven't been added, and don't re-add ones already installed.
- Find components —
npx shadcn@latest search.
- Get docs and examples — run
npx shadcn@latest docs <component> to get URLs, then fetch them. Use npx shadcn@latest view to browse registry items you haven't installed. To preview changes to installed components, use npx shadcn@latest add --diff.
- Install or update —
npx shadcn@latest add. When updating existing components, use --dry-run and --diff to preview changes first (see Updating Components below).
- Fix imports in third-party components — After adding components from community registries (e.g.
@bundui, @magicui), check the added non-UI files for hardcoded import paths like @/components/ui/.... These won't match the project's actual aliases. Use npx shadcn@latest info to get the correct ui alias (e.g. @workspace/ui/components) and rewrite the imports accordingly. The CLI rewrites imports for its own UI files, but third-party registry components may use default paths that don't match the project.
- Review added components — After adding a component or block from any registry, always read the added files and verify they are correct. Check for missing sub-components (e.g.
SelectItem without SelectGroup), missing imports, incorrect composition, or violations of the Critical Rules. Also replace any icon imports with the project's iconLibrary from the project context (e.g. if the registry item uses lucide-react but the project uses hugeicons, swap the imports and icon names accordingly). Fix all issues before moving on.
- Registry must be explicit — When the user asks to add a block or component, do not guess the registry. If no registry is specified (e.g. user says "add a login block" without specifying
@shadcn, @tailark, owner/repo, etc.), ask which registry to use. Never default to a registry on behalf of the user.
- Switching presets — Ask the user first: overwrite, partial, merge, or skip?
- Inspect current preset:
npx shadcn@latest preset resolve. Use --json when you need structured values.
- Inspect incoming preset:
npx shadcn@latest preset decode <code>. Use preset url <code> or preset open <code> to share or open the preset builder.
- Overwrite:
npx shadcn@latest apply <code>. Overwrites detected components, fonts, and CSS variables.
- Partial:
npx shadcn@latest apply <code> --only theme,font. Updates only the selected preset parts without reinstalling UI components. Supported values are theme and font; comma-separated combinations are allowed. icon is intentionally not supported, because icon changes may require full component reinstall and transforms.
- Merge:
npx shadcn@latest init --preset <code> --force --no-reinstall, then run npx shadcn@latest info to list installed components, then for each installed component use --dry-run and --diff to smart merge it individually.
- Skip:
npx shadcn@latest init --preset <code> --force --no-reinstall. Only updates config and CSS, leaves components as-is.
- Important: Always run preset commands inside the user's project directory.
apply only works in an existing project with a components.json file. The CLI automatically preserves the current base (base vs radix) from components.json. If you must use a scratch/temp directory (e.g. for --dry-run comparisons), pass --base <current-base> explicitly — preset codes do not encode the base.
Updating Components
When the user asks to update a component from upstream while keeping their local changes, use --dry-run and --diff to intelligently merge. NEVER fetch raw files from GitHub manually — always use the CLI.
- 运行
npx shadcn@latest add <component> --dry-run 查看将受影响的所有文件。
- 对每个文件,运行
npx shadcn@latest add <component> --diff <file> 查看上游与本地之间的更改。
- 根据差异针对每个文件决定:
- 无本地更改 → 可安全覆盖。
- 有本地更改 → 读取本地文件,分析差异,在保留本地修改的同时应用上游更新。
- 用户说"直接更新全部" → 使用
--overwrite,但需先确认。
- 未经用户明确批准,切勿使用
--overwrite。
快速参考
npx shadcn@latest init --name my-app --preset base-nova
npx shadcn@latest init --name my-app --preset a2r6bw --template vite
npx shadcn@latest init --name my-app --preset base-nova --monorepo
npx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
npx shadcn@latest init --preset base-nova
npx shadcn@latest init --defaults
npx shadcn@latest apply a2r6bw
npx shadcn@latest apply a2r6bw --only theme
npx shadcn@latest apply a2r6bw --only font
npx shadcn@latest apply a2r6bw --only theme,font
npx shadcn@latest preset decode a2r6bw
npx shadcn@latest preset url a2r6bw
npx shadcn@latest preset open a2r6bw
npx shadcn@latest preset resolve
npx shadcn@latest preset resolve --json
npx shadcn@latest add button card dialog
npx shadcn@latest add @magicui/shimmer-button
npx shadcn@latest add owner/repo/item
npx shadcn@latest add --all
npx shadcn@latest add button --dry-run
npx shadcn@latest add button --diff button.tsx
npx shadcn@latest add @acme/form --view button.tsx
npx shadcn@latest add owner/repo/item --dry-run
npx shadcn@latest search @shadcn -q "sidebar"
npx shadcn@latest search @tailark -q "stats"
npx shadcn@latest search owner/repo -q "login"
npx shadcn@latest search
npx shadcn@latest search @shadcn -q "menu" -t ui
npx shadcn@latest docs button dialog select
npx shadcn@latest view @shadcn/button
npx shadcn@latest view owner/repo/item
Named presets: nova, vega, maia, lyra, mira, luma
Templates: next, vite, start, react-router, astro (all support --monorepo) and laravel (not supported for monorepo)
Preset codes: Version-prefixed base62 strings (e.g. a2r6bw or b0), from ui.shadcn.com.
详细参考
- rules/forms.md — FieldGroup, Field, InputGroup, ToggleGroup, FieldSet, validation states
- rules/composition.md — Groups, overlays, Card, Tabs, Avatar, Alert, Empty, Toast, Separator, Skeleton, Badge, Button loading
- rules/chat.md — MessageScroller, Message, Bubble, Attachment, Marker; streaming, anchoring, jump-to-latest
- rules/icons.md — data-icon, icon sizing, passing icons as objects
- rules/styling.md — Semantic colors, variants, className, spacing, size, truncate, dark mode, cn(), z-index
- rules/base-vs-radix.md — asChild vs render, Select, ToggleGroup, Slider, Accordion
- cli.md — Commands, flags, presets, templates
- registry.md — Authoring source registries,
include, item definitions, dependencies, GitHub registry rules
- customization.md — Theming, CSS variables, extending components