shadcn
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseshadcn/ui
shadcn/ui
A framework for building ui, components and design systems. Components are added as source code to the user's project via the CLI.
IMPORTANT: Run all CLI commands using the project's package runner:,npx shadcn@latest, orpnpm dlx shadcn@latest— based on the project'sbunx --bun shadcn@latest. Examples below usepackageManagerbut substitute the correct runner for the project.npx shadcn@latest
一个用于构建UI、组件和设计系统的框架。组件会通过CLI以源代码的形式添加到用户项目中。
重要提示: 请根据项目的使用对应的包运行器执行所有CLI命令:packageManager、npx shadcn@latest或pnpm dlx shadcn@latest。以下示例使用bunx --bun shadcn@latest,请根据项目实际情况替换为正确的运行器。npx shadcn@latest
Current Project Context
当前项目上下文
json
!`npx shadcn@latest info --json 2>/dev/null || echo '{"error": "No shadcn project found. Run shadcn init first."}'`The JSON above contains the project config and installed components. Use to get documentation and example URLs for any component.
npx shadcn@latest docs <component>json
!`npx shadcn@latest info --json 2>/dev/null || echo '{"error": "No shadcn project found. Run shadcn init first."}'`上述JSON包含项目配置和已安装的组件信息。你可以使用获取任意组件的文档和示例URL。
npx shadcn@latest docs <component>Principles
原则
- Use existing components first. Use to check registries before writing custom UI. Check community registries too.
npx shadcn@latest search - Compose, don't reinvent. Settings page = Tabs + Card + form controls. Dashboard = Sidebar + Card + Chart + Table.
- Use built-in variants before custom styles. ,
variant="outline", etc.size="sm" - Use semantic colors. ,
bg-primary— never raw values liketext-muted-foreground.bg-blue-500
- 优先使用现有组件。 编写自定义UI前,请使用检查注册表,也可以查看社区注册表。
npx shadcn@latest search - 组合而非重造。 设置页 = Tabs + Card + 表单控件;仪表盘 = Sidebar + Card + Chart + Table。
- 自定义样式前优先使用内置变体。 例如、
variant="outline"等。size="sm" - 使用语义化颜色。 例如、
bg-primary,绝对不要使用text-muted-foreground这类原始值。bg-blue-500
Critical Rules
关键规则
These rules are always enforced. Each links to a file with Incorrect/Correct code pairs.
以下规则始终强制执行,每条规则都关联了包含错误/正确代码示例的文件。
Styling & Tailwind → styling.md
样式与Tailwind → styling.md
- for layout, not styling. Never override component colors or typography.
className - No or
space-x-*. Usespace-y-*withflex. For vertical stacks,gap-*.flex flex-col gap-* - Use when width and height are equal.
size-*notsize-10.w-10 h-10 - Use shorthand. Not
truncate.overflow-hidden text-ellipsis whitespace-nowrap - No manual color overrides. Use semantic tokens (
dark:,bg-background).text-muted-foreground - Use for conditional classes. Don't write manual template literal ternaries.
cn() - No manual on overlay components. Dialog, Sheet, Popover, etc. handle their own stacking.
z-index
- 仅用于布局,不用于样式。 不要重写组件的颜色或排版样式。
className - 禁止使用或
space-x-*。 使用带space-y-*的gap-*布局,垂直堆叠请使用flex。flex flex-col gap-* - 宽高相等时使用。 用
size-*而非size-10。w-10 h-10 - 使用简写。 不要写
truncate。overflow-hidden text-ellipsis whitespace-nowrap - 禁止手动覆盖颜色。 请使用语义化token(
dark:、bg-background)。text-muted-foreground - 使用处理条件类名。 不要手动写模板字符串三元表达式。
cn() - 禁止在浮层组件上手动设置。 Dialog、Sheet、Popover等组件会自行处理层级。
z-index
Forms & Inputs → forms.md
表单与输入组件 → forms.md
- Forms use +
FieldGroup. Never use rawFieldwithdivorspace-y-*for form layout.grid gap-* - uses
InputGroup/InputGroupInput. Never rawInputGroupTextarea/InputinsideTextarea.InputGroup - Buttons inside inputs use +
InputGroup.InputGroupAddon - Option sets (2–7 choices) use . Don't loop
ToggleGroupwith manual active state.Button - +
FieldSetfor grouping related checkboxes/radios. Don't use aFieldLegendwith a heading.div - Field validation uses +
data-invalid.aria-invalidondata-invalid,Fieldon the control. For disabled:aria-invalidondata-disabled,Fieldon the control.disabled
- 表单使用+
FieldGroup。 不要直接用带Field或space-y-*的grid gap-*做表单布局。div - 内使用
InputGroup/InputGroupInput。 不要在InputGroupTextarea内直接使用原生InputGroup/Input。Textarea - 输入框内的按钮请使用+
InputGroup。InputGroupAddon - 2-7个选项的选项集使用。 不要循环渲染
ToggleGroup并手动管理激活状态。Button - 相关的复选框/单选框使用+
FieldSet分组。 不要用带标题的FieldLegend。div - 字段验证使用+
data-invalid。aria-invalid上添加Field,控件上添加data-invalid。禁用状态:aria-invalid上添加Field,控件上添加data-disabled。disabled
Component Structure → composition.md
组件结构 → composition.md
- Items always inside their Group. →
SelectItem.SelectGroup→DropdownMenuItem.DropdownMenuGroup→CommandItem.CommandGroup - Use (radix) or
asChild(base) for custom triggers. Checkrenderfield frombase. → base-vs-radix.mdnpx shadcn@latest info - Dialog, Sheet, and Drawer always need a Title. ,
DialogTitle,SheetTitlerequired for accessibility. UseDrawerTitleif visually hidden.className="sr-only" - Use full Card composition. /
CardHeader/CardTitle/CardDescription/CardContent. Don't dump everything inCardFooter.CardContent - Button has no /
isPending. Compose withisLoading+Spinner+data-icon.disabled - must be inside
TabsTrigger. Never render triggers directly inTabsList.Tabs - always needs
Avatar. For when the image fails to load.AvatarFallback
- 条目始终放在对应的组内。 →
SelectItem;SelectGroup→DropdownMenuItem;DropdownMenuGroup→CommandItem。CommandGroup - 自定义触发器使用(radix)或
asChild(base)。 可以通过render的npx shadcn@latest info字段判断 → base-vs-radix.mdbase - Dialog、Sheet、Drawer必须包含标题。 为了可访问性,必须提供、
DialogTitle、SheetTitle,如果不需要视觉展示可以加DrawerTitle。className="sr-only" - 使用完整的Card组合结构。 /
CardHeader/CardTitle/CardDescription/CardContent,不要把所有内容都放在CardFooter里。CardContent - Button没有/
isPending属性。 请组合使用isLoading+Spinner+data-icon实现。disabled - 必须放在
TabsTrigger内。 不要直接在TabsList中渲染触发器。Tabs - 必须包含
Avatar。 用于图片加载失败的降级展示。AvatarFallback
Use Components, Not Custom Markup → composition.md
使用组件而非自定义标签 → composition.md
- Use existing components before custom markup. Check if a component exists before writing a styled .
div - Callouts use . Don't build custom styled divs.
Alert - Empty states use . Don't build custom empty state markup.
Empty - Toast via . Use
sonnerfromtoast().sonner - Use instead of
Separatoror<hr>.<div className="border-t"> - Use for loading placeholders. No custom
Skeletondivs.animate-pulse - Use instead of custom styled spans.
Badge
- 自定义标签前优先使用现有组件。 写带样式的前先检查是否已有对应组件。
div - 提示框使用。 不要自己写自定义样式的div。
Alert - 空状态使用。 不要自己写空状态的自定义标签。
Empty - Toast通过实现。 使用
sonner导出的sonner方法。toast() - 使用代替
Separator或<hr>。<div className="border-t"> - 使用做加载占位符,不要自定义
Skeleton的div。animate-pulse - 使用代替自定义样式的span。
Badge
Icons → icons.md
图标 → icons.md
- Icons in use
Button.data-iconordata-icon="inline-start"on the icon.data-icon="inline-end" - No sizing classes on icons inside components. Components handle icon sizing via CSS. No or
size-4.w-4 h-4 - Pass icons as objects, not string keys. , not a string lookup.
icon={CheckIcon}
- 内的图标添加
Button属性。 图标上添加data-icon或data-icon="inline-start"。data-icon="inline-end" - 组件内的图标不要加尺寸类。 组件会通过CSS处理图标尺寸,不要加或
size-4。w-4 h-4 - 图标以对象形式传递,不要用字符串key。 用,不要用字符串查找。
icon={CheckIcon}
CLI
CLI
- Never decode or fetch preset codes manually. Pass them directly to .
npx shadcn@latest init --preset <code>
- 不要手动解码或拉取预设代码。 直接传递给即可。
npx shadcn@latest init --preset <code>
Key Patterns
核心模式
These are the most common patterns that differentiate correct shadcn/ui code. For edge cases, see the linked rule files above.
tsx
// Form layout: FieldGroup + Field, not div + Label.
<FieldGroup>
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input id="email" />
</Field>
</FieldGroup>
// Validation: data-invalid on Field, aria-invalid on the control.
<Field data-invalid>
<FieldLabel>Email</FieldLabel>
<Input aria-invalid />
<FieldDescription>Invalid email.</FieldDescription>
</Field>
// Icons in buttons: data-icon, no sizing classes.
<Button>
<SearchIcon data-icon="inline-start" />
Search
</Button>
// Spacing: gap-*, not space-y-*.
<div className="flex flex-col gap-4"> // correct
<div className="space-y-4"> // wrong
// Equal dimensions: size-*, not w-* h-*.
<Avatar className="size-10"> // correct
<Avatar className="w-10 h-10"> // wrong
// Status colors: Badge variants or semantic tokens, not raw colors.
<Badge variant="secondary">+20.1%</Badge> // correct
<span className="text-emerald-600">+20.1%</span> // wrong以下是区分shadcn/ui代码是否规范的最常见模式,边缘情况请参考上面关联的规则文件。
tsx
// 表单布局:FieldGroup + Field,不要用div + Label
<FieldGroup>
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input id="email" />
</Field>
</FieldGroup>
// 校验:Field上添加data-invalid,控件上添加aria-invalid
<Field data-invalid>
<FieldLabel>Email</FieldLabel>
<Input aria-invalid />
<FieldDescription>Invalid email.</FieldDescription>
</Field>
// 按钮内的图标:添加data-icon,不要加尺寸类
<Button>
<SearchIcon data-icon="inline-start" />
Search
</Button>
// 间距:用gap-*,不要用space-y-*
<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变体或语义化token,不要用原始颜色
<Badge variant="secondary">+20.1%</Badge> // 正确
<span className="text-emerald-600">+20.1%</span> // 错误Component Selection
组件选择
| Need | Use |
|---|---|
| Button/action | |
| Form inputs | |
| Toggle between 2–5 options | |
| Data display | |
| Navigation | |
| Overlays | |
| Feedback | |
| Command palette | |
| Charts | |
| Layout | |
| Empty states | |
| Menus | |
| Tooltips/info | |
| 需求 | 推荐组件 |
|---|---|
| 按钮/操作按钮 | 对应变体的 |
| 表单输入 | |
| 2-5个选项的切换 | |
| 数据展示 | |
| 导航 | |
| 浮层 | |
| 反馈提示 | |
| 命令面板 | |
| 图表 | 封装了Recharts的 |
| 布局 | |
| 空状态 | |
| 菜单 | |
| 提示/信息展示 | |
Key Fields
关键字段
The injected project context contains these key fields:
- → use the actual alias prefix for imports (e.g.
aliases,@/), never hardcode.~/ - → when
isRSC, components usingtrue,useState, event handlers, or browser APIs needuseEffectat the top of the file. Always reference this field when advising on the directive."use client" - →
tailwindVersionuses"v4"blocks;@theme inlineuses"v3".tailwind.config.js - → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.
tailwindCssFile - → component visual treatment (e.g.
style,nova).vega - → primitive library (
baseorradix). Affects component APIs and available props.base - → determines icon imports. Use
iconLibraryforlucide-react,lucidefor@tabler/icons-react, etc. Never assumetabler.lucide-react - → exact file-system destinations for components, utils, hooks, etc.
resolvedPaths - → routing and file conventions (e.g. Next.js App Router vs Vite SPA).
framework - → use this for any non-shadcn dependency installs (e.g.
packageManagervspnpm add date-fns).npm install date-fns
See cli.md — command for the full field reference.
info注入的项目上下文包含以下关键字段:
- → 使用实际的导入别名前缀(例如
aliases、@/),绝对不要硬编码。~/ - → 当值为
isRSC时,使用true、useState、事件处理器或浏览器API的组件需要在文件顶部添加useEffect指令,给出相关建议时务必参考此字段。"use client" - →
tailwindVersion使用"v4"块;@theme inline使用"v3"。tailwind.config.js - → 定义自定义CSS变量的全局CSS文件,始终修改此文件,不要新建。
tailwindCssFile - → 组件的视觉风格(例如
style、nova)。vega - → 基础组件库(
base或radix),会影响组件API和可用属性。base - → 决定图标导入方式,
iconLibrary对应lucide,lucide-react对应tabler等,不要默认假设是@tabler/icons-react。lucide-react - → 组件、工具函数、Hook等的精确文件系统路径。
resolvedPaths - → 路由和文件约定(例如Next.js App Router与Vite SPA的区别)。
framework - → 安装非shadcn依赖时使用对应的包管理器(例如
packageManager和pnpm add date-fns的区别)。npm install date-fns
完整字段参考请查看 cli.md — 命令。
infoComponent Docs, Examples, and Usage
组件文档、示例与使用
Run 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 <component>bash
npx shadcn@latest docs button dialog selectWhen creating, fixing, debugging, or using a component, always run and fetch the URLs first. This ensures you're working with the correct API and usage patterns rather than guessing.
npx shadcn@latest docs运行获取组件的文档、示例和API参考URL,拉取这些URL获取实际内容。
npx shadcn@latest docs <component>bash
npx shadcn@latest docs button dialog select在创建、修复、调试或使用组件时,务必先运行拉取对应的URL内容。 这样可以确保你使用的是正确的API和使用模式,而非猜测。
npx shadcn@latest docsWorkflow
工作流
- Get project context — already injected above. Run again if you need to refresh.
npx shadcn@latest info - Check installed components first — before running , always check the
addlist from project context or list thecomponentsdirectory. Don't import components that haven't been added, and don't re-add ones already installed.resolvedPaths.ui - Find components — .
npx shadcn@latest search - Get docs and examples — run to get URLs, then fetch them. Use
npx shadcn@latest docs <component>to browse registry items you haven't installed. To preview changes to installed components, usenpx shadcn@latest view.npx shadcn@latest add --diff - Install or update — . When updating existing components, use
npx shadcn@latest addand--dry-runto preview changes first (see Updating Components below).--diff - Fix imports in third-party components — After adding components from community registries (e.g. ,
@bundui), check the added non-UI files for hardcoded import paths like@magicui. These won't match the project's actual aliases. Use@/components/ui/...to get the correctnpx shadcn@latest infoalias (e.g.ui) 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.@workspace/ui/components - 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. without
SelectItem), missing imports, incorrect composition, or violations of the Critical Rules. Also replace any icon imports with the project'sSelectGroupfrom the project context (e.g. if the registry item usesiconLibrarybut the project useslucide-react, swap the imports and icon names accordingly). Fix all issues before moving on.hugeicons - 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, etc.), ask which registry to use. Never default to a registry on behalf of the user.@tailark - Switching presets — Ask the user first: reinstall, merge, or skip?
- Reinstall: . Overwrites all components.
npx shadcn@latest init --preset <code> --force --reinstall - Merge: , then run
npx shadcn@latest init --preset <code> --force --no-reinstallto list installed components, then for each installed component usenpx shadcn@latest infoand--dry-runto smart merge it individually.--diff - Skip: . Only updates config and CSS, leaves components as-is.
npx shadcn@latest init --preset <code> --force --no-reinstall
- Reinstall:
- 获取项目上下文 — 已经在上方注入,如需刷新可以重新运行。
npx shadcn@latest info - 优先检查已安装组件 — 运行命令前,始终先检查项目上下文中的
add列表,或查看components目录。不要导入未添加的组件,也不要重复安装已有的组件。resolvedPaths.ui - 查找组件 — 运行。
npx shadcn@latest search - 获取文档和示例 — 运行获取URL并拉取内容。使用
npx shadcn@latest docs <component>浏览尚未安装的注册表项,预览已安装组件的变更可以使用npx shadcn@latest view。npx shadcn@latest add --diff - 安装或更新 — 运行。更新现有组件时,先使用
npx shadcn@latest add和--dry-run预览变更(参考下文更新组件)。--diff - 修复第三方组件的导入路径 — 从社区注册表(例如、
@bundui)添加组件后,检查新增的非UI文件是否存在硬编码的导入路径,例如@magicui,这类路径可能和项目的实际别名不匹配。使用@/components/ui/...获取正确的npx shadcn@latest info别名(例如ui)并重写对应的导入。CLI会自动重写自身UI文件的导入,但第三方注册表组件可能使用和项目不匹配的默认路径。@workspace/ui/components - 审核新增的组件 — 从任何注册表添加组件或区块后,务必阅读新增的文件并验证正确性。检查是否缺少子组件(例如没有的
SelectGroup)、缺少导入、组合方式错误或违反关键规则。同时将所有图标导入替换为项目上下文中SelectItem对应的导入(例如如果注册表项使用iconLibrary但项目使用lucide-react,需要对应替换导入和图标名称),修复所有问题后再继续。hugeicons - 注册表必须明确指定 — 用户要求添加区块或组件时,不要猜测注册表。如果没有指定注册表(例如用户说「添加登录区块」但没有指定、
@shadcn等),询问用户要使用哪个注册表,绝对不要替用户默认选择注册表。@tailark - 切换预设 — 先询问用户选择:重新安装、合并 还是 跳过?
- 重新安装:,会覆盖所有组件。
npx shadcn@latest init --preset <code> --force --reinstall - 合并:,然后运行
npx shadcn@latest init --preset <code> --force --no-reinstall列出已安装组件,对每个已安装组件使用npx shadcn@latest info和--dry-run进行智能合并。--diff - 跳过:,仅更新配置和CSS,保留现有组件不变。
npx shadcn@latest init --preset <code> --force --no-reinstall
- 重新安装:
Updating Components
更新组件
When the user asks to update a component from upstream while keeping their local changes, use and to intelligently merge. NEVER fetch raw files from GitHub manually — always use the CLI.
--dry-run--diff- Run to see all files that would be affected.
npx shadcn@latest add <component> --dry-run - For each file, run to see what changed upstream vs local.
npx shadcn@latest add <component> --diff <file> - Decide per file based on the diff:
- No local changes → safe to overwrite.
- Has local changes → read the local file, analyze the diff, and apply upstream updates while preserving local modifications.
- User says "just update everything" → use , but confirm first.
--overwrite
- Never use without the user's explicit approval.
--overwrite
用户要求从上游更新组件同时保留本地修改时,使用和进行智能合并。绝对不要手动从GitHub拉取原始文件,始终使用CLI。
--dry-run--diff- 运行查看所有会受影响的文件。
npx shadcn@latest add <component> --dry-run - 对每个文件运行查看上游和本地的差异。
npx shadcn@latest add <component> --diff <file> - 根据diff逐文件决定处理方式:
- 无本地修改 → 可以安全覆盖。
- 有本地修改 → 阅读本地文件,分析diff,在保留本地修改的同时应用上游更新。
- 用户要求「全部更新」 → 使用,但必须先确认。
--overwrite
- 没有用户明确批准前绝对不要使用。
--overwrite
Quick Reference
快速参考
bash
undefinedbash
undefinedCreate a new project.
创建新项目
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
npx shadcn@latest init --name my-app --preset a2r6bw --template vite
Create a monorepo project.
创建monorepo项目
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 --name my-app --preset base-nova --monorepo
npx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
Initialize existing project.
初始化现有项目
npx shadcn@latest init --preset base-nova
npx shadcn@latest init --defaults # shortcut: --template=next --preset=base-nova
npx shadcn@latest init --preset base-nova
npx shadcn@latest init --defaults # 快捷方式:--template=next --preset=base-nova
Add components.
添加组件
npx shadcn@latest add button card dialog
npx shadcn@latest add @magicui/shimmer-button
npx shadcn@latest add --all
npx shadcn@latest add button card dialog
npx shadcn@latest add @magicui/shimmer-button
npx shadcn@latest add --all
Preview changes before adding/updating.
添加/更新前预览变更
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 button --dry-run
npx shadcn@latest add button --diff button.tsx
npx shadcn@latest add @acme/form --view button.tsx
Search registries.
搜索注册表
npx shadcn@latest search @shadcn -q "sidebar"
npx shadcn@latest search @tailark -q "stats"
npx shadcn@latest search @shadcn -q "sidebar"
npx shadcn@latest search @tailark -q "stats"
Get component docs and example URLs.
获取组件文档和示例URL
npx shadcn@latest docs button dialog select
npx shadcn@latest docs button dialog select
View registry item details (for items not yet installed).
查看注册表项详情(适用于尚未安装的项)
npx shadcn@latest view @shadcn/button
**Named presets:** `base-nova`, `radix-nova`
**Templates:** `next`, `vite`, `start`, `react-router`, `astro` (all support `--monorepo`) and `laravel` (not supported for monorepo)
**Preset codes:** Base62 strings starting with `a` (e.g. `a2r6bw`), from [ui.shadcn.com](https://ui.shadcn.com).npx shadcn@latest view @shadcn/button
**命名预设:** `base-nova`、`radix-nova`
**模板:** `next`、`vite`、`start`、`react-router`、`astro`(均支持`--monorepo`)和`laravel`(不支持monorepo)
**预设代码:** 以`a`开头的Base62字符串(例如`a2r6bw`),来自[ui.shadcn.com](https://ui.shadcn.com)。Detailed References
详细参考
- 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/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
- customization.md — Theming, CSS variables, extending components
- rules/forms.md — FieldGroup、Field、InputGroup、ToggleGroup、FieldSet、校验状态
- rules/composition.md — 组、浮层、Card、Tabs、Avatar、Alert、Empty、Toast、Separator、Skeleton、Badge、Button加载状态
- rules/icons.md — data-icon、图标尺寸、对象形式传递图标
- rules/styling.md — 语义化颜色、变体、className、间距、size、truncate、暗黑模式、cn()、z-index
- rules/base-vs-radix.md — asChild与render的区别、Select、ToggleGroup、Slider、Accordion
- cli.md — 命令、参数、预设、模板
- customization.md — 主题、CSS变量、组件扩展