shadcn

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

shadcn/ui

shadcn/ui

You are an expert in shadcn/ui — a collection of beautifully designed, accessible, and customizable React components built on Radix UI primitives and Tailwind CSS. Components are added directly to your codebase as source code, not installed as a dependency.
您是shadcn/ui方面的专家——这是一套基于Radix UI基础组件和Tailwind CSS构建的、设计精美、易用且可自定义的React组件集合。组件会以源代码形式直接添加到您的代码库中,而非作为依赖包安装。

Key Concept

核心概念

shadcn/ui is not a component library in the traditional sense. You don't install it as a package. Instead, the CLI copies component source code into your project, giving you full ownership and customization ability.
shadcn/ui 并非传统意义上的组件库。您无需将其作为包安装,而是通过CLI将组件源代码复制到您的项目中,让您拥有完全的所有权和自定义能力。

CLI Commands

CLI命令

Initialize (non-interactive — ALWAYS use this)

初始化(非交互式——请始终使用此方式)

IMPORTANT:
shadcn init
is interactive by default. Always use
-d
(defaults) for non-interactive initialization:
bash
undefined
重要提示:默认情况下
shadcn init
是交互式的。请始终使用
-d
(默认配置)参数进行非交互式初始化:
bash
undefined

Non-interactive init with defaults — USE THIS

带默认配置的非交互式初始化——请使用此命令

npx shadcn@latest init -d
npx shadcn@latest init -d

Non-interactive with a preset (recommended for consistent design systems)

使用预设的非交互式初始化(推荐用于一致的设计系统)

npx shadcn@latest init --preset <code> -f
npx shadcn@latest init --preset <code> -f

Non-interactive with explicit base library choice

明确指定基础库的非交互式初始化

npx shadcn@latest init -d --base radix npx shadcn@latest init -d --base base-ui
npx shadcn@latest init -d --base radix npx shadcn@latest init -d --base base-ui

Scaffold a full project template (CLI v4)

搭建完整项目模板(CLI v4)


> **AI Elements compatibility**: Always use `--base radix` (the default) when the project uses or may use AI Elements. AI Elements components rely on Radix APIs and have type errors with Base UI.

```bash
npx shadcn@latest init --template next -d
npx shadcn@latest init --template vite -d
Options:
  • -d, --defaults
    Use default configuration, skip all interactive prompts (REQUIRED for CI/agent use)
  • -y, --yes
    — Skip confirmation prompts (does NOT skip library selection — use
    -d
    instead)
  • -f, --force
    — Force overwrite existing configuration
  • -t, --template
    — Scaffold full project template (
    next
    ,
    vite
    ,
    react-router
    ,
    astro
    ,
    laravel
    ,
    tanstack-start
    )
  • --preset
    — Apply a design system preset (colors, theme, icons, fonts, radius) as a single shareable code
  • --base
    — Choose primitive library:
    radix
    (default) or
    base-ui
  • --monorepo
    — Set up a monorepo structure
WARNING:
-y
/
--yes
alone does NOT make init fully non-interactive — it still prompts for component library selection. Always use
-d
to skip ALL prompts.
Deprecated in CLI v4:
--style
,
--base-color
,
--src-dir
,
--no-base-style
, and
--css-variables
flags are removed and will error. The
registry:build
and
registry:mcp
registry types are also deprecated. Use
registry:base
and
registry:font
instead.
The init command:
  1. Detects your framework (Next.js, Vite, React Router, Astro, Laravel, TanStack Start)
  2. Installs required dependencies (Radix UI, tailwind-merge, class-variance-authority)
  3. Creates
    components.json
    configuration
  4. Sets up the
    cn()
    utility function
  5. Configures CSS variables for theming

> **AI Elements兼容性**:当项目使用或可能使用AI Elements时,请始终使用`--base radix`(默认选项)。AI Elements组件依赖Radix API,与Base UI搭配会出现类型错误。

```bash
npx shadcn@latest init --template next -d
npx shadcn@latest init --template vite -d
选项说明:
  • -d, --defaults
    —— 使用默认配置,跳过所有交互式提示(CI/代理场景必填)
  • -y, --yes
    —— 跳过确认提示(不会跳过库选择——请使用
    -d
    替代)
  • -f, --force
    —— 强制覆盖现有配置
  • -t, --template
    —— 搭建完整项目模板(可选值:
    next
    ,
    vite
    ,
    react-router
    ,
    astro
    ,
    laravel
    ,
    tanstack-start
  • --preset
    —— 应用设计系统预设(包含颜色、主题、图标、字体、圆角),通过单个共享代码实现
  • --base
    —— 选择基础组件库:
    radix
    (默认)或
    base-ui
  • --monorepo
    —— 设置 monorepo 结构
警告:仅使用
-y
/
--yes
参数无法实现完全非交互式初始化——它仍会提示选择组件库。请始终使用
-d
来跳过所有提示。
CLI v4中已废弃
--style
--base-color
--src-dir
--no-base-style
--css-variables
参数已被移除,使用会报错。
registry:build
registry:mcp
注册表类型也已废弃,请使用
registry:base
registry:font
替代。
初始化命令会执行以下操作:
  1. 检测您的框架(Next.js、Vite、React Router、Astro、Laravel、TanStack Start)
  2. 安装所需依赖(Radix UI、tailwind-merge、class-variance-authority)
  3. 创建
    components.json
    配置文件
  4. 设置
    cn()
    工具函数
  5. 配置用于主题的CSS变量

Add Components

添加组件

bash
undefined
bash
undefined

Add specific components

添加指定组件

npx shadcn@latest add button dialog card
npx shadcn@latest add button dialog card

Add all available components

添加所有可用组件

npx shadcn@latest add --all
npx shadcn@latest add --all

Add from a custom registry

从自定义注册表添加

npx shadcn@latest add @v0/dashboard npx shadcn@latest add @acme/custom-button
npx shadcn@latest add @v0/dashboard npx shadcn@latest add @acme/custom-button

Add from AI Elements registry

从AI Elements注册表添加


Options:
- `-o, --overwrite` — Overwrite existing files
- `-p, --path` — Custom install path
- `-a, --all` — Install all components
- `--dry-run` — Preview what will be added without writing files
- `--diff` — Show diff of changes when updating existing components
- `--view` — Display a registry item's source code inline

选项说明:
- `-o, --overwrite` —— 覆盖现有文件
- `-p, --path` —— 自定义安装路径
- `-a, --all` —— 安装所有组件
- `--dry-run` —— 预览将添加的内容但不写入文件
- `--diff` —— 更新现有组件时显示变更差异
- `--view` —— 内联显示注册表项的源代码

Search & List

搜索与列出

bash
npx shadcn@latest search button
npx shadcn@latest list @v0
bash
npx shadcn@latest search button
npx shadcn@latest list @v0

Build (Custom Registry)

构建(自定义注册表)

bash
npx shadcn@latest build
npx shadcn@latest build ./registry.json -o ./public/r
bash
npx shadcn@latest build
npx shadcn@latest build ./registry.json -o ./public/r

View, Info & Docs (CLI v4)

查看、信息与文档(CLI v4)

bash
undefined
bash
undefined

View a registry item's source before installing

安装前查看注册表项的源代码

npx shadcn@latest view button
npx shadcn@latest view button

Show project diagnostics — config, installed components, dependencies

显示项目诊断信息——配置、已安装组件、依赖

npx shadcn@latest info
npx shadcn@latest info

Get docs, code, and examples for any component (agent-friendly output)

获取任意组件的文档、代码和示例(适配代理的输出格式)

npx shadcn@latest docs button npx shadcn@latest docs dialog

> **`shadcn docs`** gives coding agents the context to use primitives correctly — returns code examples, API reference, and usage patterns inline.
npx shadcn@latest docs button npx shadcn@latest docs dialog

> **`shadcn docs`** 可为编码代理提供正确使用基础组件的上下文——会内联返回代码示例、API参考和使用模式。

Migrate

迁移

bash
npx shadcn@latest migrate rtl    # RTL support migration
npx shadcn@latest migrate radix  # Migrate to unified radix-ui package
npx shadcn@latest migrate icons  # Icon library changes
bash
npx shadcn@latest migrate rtl    # 迁移以支持RTL(从右到左)布局
npx shadcn@latest migrate radix  # 迁移到统一的radix-ui包
npx shadcn@latest migrate icons  # 图标库变更迁移

Migrate components outside the default ui directory

将组件迁移到默认ui目录之外

npx shadcn@latest migrate radix src/components/custom
undefined
npx shadcn@latest migrate radix src/components/custom
undefined

shadcn/skills (CLI v4)

shadcn/skills(CLI v4)

shadcn/skills gives coding agents the context they need to work with components and registries correctly. It covers both Radix and Base UI primitives, updated APIs, component patterns, and registry workflows. The skill knows how to use the CLI, when to invoke it, and which flags to pass — so agents produce code that matches your design system.
Install:
pnpm dlx skills add shadcn/ui
shadcn/skills为编码代理提供正确使用组件和注册表所需的上下文信息。它涵盖Radix和Base UI基础组件、更新后的API、组件模式以及注册表工作流程。该技能知道如何使用CLI、何时调用CLI以及传递哪些参数——确保代理生成的代码与您的设计系统匹配。
安装命令:
pnpm dlx skills add shadcn/ui

Unified Radix UI Package (February 2026)

统一Radix UI包(2026年2月)

The
new-york
style now uses a single
radix-ui
package instead of individual
@radix-ui/react-*
packages:
tsx
// OLD — individual packages
import * as DialogPrimitive from "@radix-ui/react-dialog"

// NEW — unified package
import { Dialog as DialogPrimitive } from "radix-ui"
To migrate existing projects:
npx shadcn@latest migrate radix
. After migration, remove unused
@radix-ui/react-*
packages from
package.json
.
new-york
风格现在使用单个
radix-ui
包,而非独立的
@radix-ui/react-*
包:
tsx
// 旧方式——独立包
import * as DialogPrimitive from "@radix-ui/react-dialog"

// 新方式——统一包
import { Dialog as DialogPrimitive } from "radix-ui"
迁移现有项目:执行
npx shadcn@latest migrate radix
。迁移完成后,从
package.json
中移除未使用的
@radix-ui/react-*
包。

Base UI Support (January 2026)

Base UI支持(2026年1月)

shadcn/ui now supports Base UI as an alternative to Radix UI for the underlying primitive library. Components look and behave the same way regardless of which library you choose — only the underlying implementation changes.
Choose during init:
npx shadcn@latest init --base base-ui
The CLI pulls the correct component variant based on your project configuration automatically.
shadcn/ui现在支持Base UI作为Radix UI之外的另一种基础组件库选项。无论您选择哪种库,组件的外观和行为都保持一致——仅底层实现会有所不同。
初始化时选择:
npx shadcn@latest init --base base-ui
CLI会根据您的项目配置自动拉取正确的组件变体。

Configuration (components.json)

配置(components.json)

The
components.json
file configures how shadcn/ui works in your project:
json
{
  "$schema": "https://ui.shadcn.com/schema.json",
  "style": "new-york",
  "rsc": true,
  "tsx": true,
  "tailwind": {
    "config": "tailwind.config.ts",
    "css": "src/app/globals.css",
    "baseColor": "zinc",  // Options: gray, neutral, slate, stone, zinc, mauve, olive, mist, taupe
    "cssVariables": true
  },
  "aliases": {
    "components": "@/components",
    "utils": "@/lib/utils",
    "ui": "@/components/ui",
    "lib": "@/lib",
    "hooks": "@/hooks"
  },
  "registries": {
    "v0": {
      "url": "https://v0.dev/chat/api/registry"
    },
    "ai-elements": {
      "url": "https://elements.ai-sdk.dev/api/registry"
    }
  }
}
components.json
文件用于配置shadcn/ui在您项目中的工作方式:
json
{
  "$schema": "https://ui.shadcn.com/schema.json",
  "style": "new-york",
  "rsc": true,
  "tsx": true,
  "tailwind": {
    "config": "tailwind.config.ts",
    "css": "src/app/globals.css",
    "baseColor": "zinc",  // 可选值:gray, neutral, slate, stone, zinc, mauve, olive, mist, taupe
    "cssVariables": true
  },
  "aliases": {
    "components": "@/components",
    "utils": "@/lib/utils",
    "ui": "@/components/ui",
    "lib": "@/lib",
    "hooks": "@/hooks"
  },
  "registries": {
    "v0": {
      "url": "https://v0.dev/chat/api/registry"
    },
    "ai-elements": {
      "url": "https://elements.ai-sdk.dev/api/registry"
    }
  }
}

Namespaced Registries

命名空间注册表

Configure multiple registries for your project:
json
{
  "registries": {
    "acme": {
      "url": "https://acme.com/registry/{name}.json"
    },
    "private": {
      "url": "https://internal.company.com/registry/{name}.json",
      "headers": {
        "Authorization": "Bearer ${REGISTRY_TOKEN}"
      }
    }
  }
}
Install using namespace syntax:
bash
npx shadcn@latest add @acme/header @private/auth-form
为项目配置多个注册表:
json
{
  "registries": {
    "acme": {
      "url": "https://acme.com/registry/{name}.json"
    },
    "private": {
      "url": "https://internal.company.com/registry/{name}.json",
      "headers": {
        "Authorization": "Bearer ${REGISTRY_TOKEN}"
      }
    }
  }
}
使用命名空间语法安装:
bash
npx shadcn@latest add @acme/header @private/auth-form

Theming

主题配置

CSS Variables

CSS变量

shadcn/ui uses CSS custom properties for theming, defined in
globals.css
:
css
@theme inline {
  --color-background: oklch(0.145 0 0);
  --color-foreground: oklch(0.985 0 0);
  --color-card: oklch(0.205 0 0);
  --color-card-foreground: oklch(0.985 0 0);
  --color-primary: oklch(0.488 0.243 264.376);
  --color-primary-foreground: oklch(0.985 0 0);
  --color-secondary: oklch(0.269 0 0);
  --color-secondary-foreground: oklch(0.985 0 0);
  --color-muted: oklch(0.269 0 0);
  --color-muted-foreground: oklch(0.708 0 0);
  --color-accent: oklch(0.269 0 0);
  --color-accent-foreground: oklch(0.985 0 0);
  --color-destructive: oklch(0.396 0.141 25.723);
  --color-border: oklch(0.269 0 0);
  --color-input: oklch(0.269 0 0);
  --color-ring: oklch(0.488 0.243 264.376);
  --radius: 0.625rem;
  /* CLI v4: radius tokens use multiplicative calc instead of additive */
  --radius-xs: calc(var(--radius) * 0.5);
  --radius-sm: calc(var(--radius) * 0.75);
  --radius-md: calc(var(--radius) * 0.875);
  --radius-lg: var(--radius);
  --radius-xl: calc(var(--radius) * 1.5);
}
shadcn/ui使用CSS自定义属性实现主题配置,这些属性定义在
globals.css
中:
css
@theme inline {
  --color-background: oklch(0.145 0 0);
  --color-foreground: oklch(0.985 0 0);
  --color-card: oklch(0.205 0 0);
  --color-card-foreground: oklch(0.985 0 0);
  --color-primary: oklch(0.488 0.243 264.376);
  --color-primary-foreground: oklch(0.985 0 0);
  --color-secondary: oklch(0.269 0 0);
  --color-secondary-foreground: oklch(0.985 0 0);
  --color-muted: oklch(0.269 0 0);
  --color-muted-foreground: oklch(0.708 0 0);
  --color-accent: oklch(0.269 0 0);
  --color-accent-foreground: oklch(0.985 0 0);
  --color-destructive: oklch(0.396 0.141 25.723);
  --color-border: oklch(0.269 0 0);
  --color-input: oklch(0.269 0 0);
  --color-ring: oklch(0.488 0.243 264.376);
  --radius: 0.625rem;
  /* CLI v4:圆角令牌使用乘法计算而非加法 */
  --radius-xs: calc(var(--radius) * 0.5);
  --radius-sm: calc(var(--radius) * 0.75);
  --radius-md: calc(var(--radius) * 0.875);
  --radius-lg: var(--radius);
  --radius-xl: calc(var(--radius) * 1.5);
}

Dark Mode

暗黑模式

For dark mode, use the
dark
class on
<html>
:
tsx
// app/layout.tsx
<html lang="en" className="dark">
Or use next-themes for toggling:
tsx
import { ThemeProvider } from 'next-themes'

<ThemeProvider attribute="class" defaultTheme="dark">
  {children}
</ThemeProvider>
要启用暗黑模式,请在
<html>
标签上添加
dark
类:
tsx
// app/layout.tsx
<html lang="en" className="dark">
或者使用next-themes实现切换:
tsx
import { ThemeProvider } from 'next-themes'

<ThemeProvider attribute="class" defaultTheme="dark">
  {children}
</ThemeProvider>

Custom Colors

自定义颜色

Add application-specific colors alongside shadcn defaults:
css
@theme inline {
  /* shadcn defaults above... */

  /* Custom app colors */
  --color-priority-urgent: oklch(0.637 0.237 15.163);
  --color-priority-high: oklch(0.705 0.213 47.604);
  --color-status-done: oklch(0.723 0.219 149.579);
}
Use in components:
tsx
<span className="text-[var(--color-priority-urgent)]">Urgent</span>
// Or with Tailwind v4 theme():
<span className="text-priority-urgent">Urgent</span>
在shadcn默认颜色之外添加应用专属颜色:
css
@theme inline {
  /* 上方为shadcn默认颜色... */

  /* 应用自定义颜色 */
  --color-priority-urgent: oklch(0.637 0.237 15.163);
  --color-priority-high: oklch(0.705 0.213 47.604);
  --color-status-done: oklch(0.723 0.219 149.579);
}
在组件中使用:
tsx
<span className="text-[var(--color-priority-urgent)]">紧急</span>
// 或结合Tailwind v4的theme()使用:
<span className="text-priority-urgent">紧急</span>

Most Common Components

最常用组件

ComponentUse Case
button
Actions, form submission
card
Content containers
dialog
Modals, confirmation prompts
input
/
textarea
Form fields
select
Dropdowns
table
Data display
tabs
View switching
command
Command palette (Cmd+K)
dropdown-menu
Context menus
popover
Floating content
tooltip
Hover hints
badge
Status indicators
avatar
User profile images
scroll-area
Scrollable containers
separator
Visual dividers
label
Form labels
sheet
Slide-out panels
skeleton
Loading placeholders
组件使用场景
button
操作按钮、表单提交
card
内容容器
dialog
模态框、确认提示
input
/
textarea
表单字段
select
下拉菜单
table
数据展示
tabs
视图切换
command
命令面板(Cmd+K)
dropdown-menu
上下文菜单
popover
悬浮内容
tooltip
悬停提示
badge
状态指示器
avatar
用户头像
scroll-area
可滚动容器
separator
视觉分隔线
label
表单标签
sheet
滑出面板
skeleton
加载占位符

Design Direction for shadcn on Vercel

Vercel生态中shadcn的设计方向

shadcn/ui is not only a component source generator. In the Vercel stack it is the default interface language. Do not stop at "the component works." Compose pages that feel deliberate, high-signal, and consistent.
shadcn/ui不仅是组件源代码生成器,在Vercel技术栈中它是默认的界面语言。不要满足于“组件能运行”,要构建出目标明确、信息清晰且风格一致的页面。

Default aesthetic for product UI

产品UI的默认美学风格

  • Prefer style:
    new-york
    for product, dashboard, AI, and admin surfaces.
  • Default to dark mode for dashboards, AI apps, internal tools, settings, and developer-facing products. Use light mode only when the product is clearly content-first or editorial.
  • Use Geist Sans for interface text and Geist Mono for code, metrics, IDs, timestamps, commands.
  • Prefer zinc, neutral, or slate as the base palette. Use one accent color through
    --color-primary
    .
  • Build core surfaces from tokens:
    bg-background
    ,
    bg-card
    ,
    text-foreground
    ,
    text-muted-foreground
    ,
    border-border
    ,
    ring-ring
    . Avoid ad-hoc hex values.
  • Keep radius consistent. The default
    --radius: 0.625rem
    is a strong baseline.
  • Use one density system per page: comfortable (
    gap-6
    /
    p-6
    /
    text-sm
    ) or compact (
    gap-4
    /
    p-4
    /
    text-sm
    ).
  • Keep icons quiet and consistent. Lucide icons at
    h-4 w-4
    or
    h-5 w-5
    .
  • 风格偏好:产品、仪表盘、AI应用和管理后台优先使用
    new-york
    风格。
  • 暗黑模式默认:仪表盘、AI应用、内部工具、设置页面和面向开发者的产品默认使用暗黑模式。仅当产品以内容或编辑为主时才使用浅色模式。
  • 字体选择:界面文本使用Geist Sans,代码、指标、ID、时间戳和命令使用Geist Mono。
  • 基础调色板:优先使用zinc、neutral或slate作为基础调色板。通过
    --color-primary
    指定一种强调色。
  • 使用令牌构建核心界面:使用
    bg-background
    bg-card
    text-foreground
    text-muted-foreground
    border-border
    ring-ring
    等令牌构建界面,避免使用随机的十六进制颜色值。
  • 保持圆角一致:默认的
    --radius: 0.625rem
    是一个优秀的基准值。
  • 每页使用统一的密度系统:舒适型(
    gap-6
    /
    p-6
    /
    text-sm
    )或紧凑型(
    gap-4
    /
    p-4
    /
    text-sm
    )。
  • 图标风格统一且低调:使用Lucide图标,尺寸为
    h-4 w-4
    h-5 w-5

Reach for this first

优先选择的组件组合

Use caseReach for this firstWhy
Settings page
Tabs
+
Card
+
Form
Clear information grouping with predictable save flows
Data dashboard
Card
+
Badge
+
Table
+
DropdownMenu
Covers summary, status, dense data, and row actions without custom shells
CRUD table
Table
+
DropdownMenu
+
Sheet
+
AlertDialog
Supports browse, act, edit, and destructive confirmation in a standard pattern
Auth screen
Card
+
Label
+
Input
+
Button
+
Alert
Keeps entry flows focused and gives errors a proper treatment
Global search
Command
+
Dialog
Fast keyboard-first discovery with an established interaction model
Mobile nav
Sheet
+
Button
+
Separator
Provides a compact navigation shell that adapts cleanly to small screens
Detail pageheader +
Badge
+
Separator
+
Card
Balances hierarchy, metadata, and supporting content without over-nesting
Filters
Card
sidebar +
Sheet
+
Select
Works for persistent desktop filters and collapsible mobile controls
Empty/loading/error states
Card
+
Skeleton
+
Alert
Gives non-happy paths a designed surface instead of placeholder text
使用场景优先选择的组件组合原因
设置页面
Tabs
+
Card
+
Form
清晰的信息分组,搭配可预测的保存流程
数据仪表盘
Card
+
Badge
+
Table
+
DropdownMenu
涵盖摘要、状态、高密度数据和行操作,无需自定义外壳
CRUD表格
Table
+
DropdownMenu
+
Sheet
+
AlertDialog
支持浏览、操作、编辑和破坏性操作确认的标准模式
认证页面
Card
+
Label
+
Input
+
Button
+
Alert
保持登录流程聚焦,错误提示有规范的展示方式
全局搜索
Command
+
Dialog
基于键盘的快速搜索,采用成熟的交互模型
移动端导航
Sheet
+
Button
+
Separator
提供紧凑的导航外壳,可完美适配小屏幕
详情页面页头 +
Badge
+
Separator
+
Card
在层级、元数据和辅助内容之间取得平衡,避免过度嵌套
筛选功能
Card
侧边栏 +
Sheet
+
Select
适用于桌面端的持久化筛选和移动端的可折叠控制
空状态/加载状态/错误状态
Card
+
Skeleton
+
Alert
为非成功状态提供经过设计的界面,而非占位文本

Composition recipes

组合示例

  • Settings page:
    Tabs
    +
    Card
    per group +
    Separator
    + save action
  • Admin dashboard: summary
    Card
    s + filter bar +
    Table
  • Entity detail: header + status
    Badge
    + main
    Card
    + side
    Card
    +
    AlertDialog
    for destructive
  • Search-heavy:
    Command
    for quick find,
    Popover
    for pickers,
    Sheet
    for mobile filters
  • Auth/onboarding: centered
    Card
    + social
    Separator
    + inline
    Alert
    for errors
  • Destructive flows:
    AlertDialog
    (not
    Dialog
    ) for confirmation
  • 设置页面:
    Tabs
    + 每组对应一个
    Card
    +
    Separator
    + 保存操作按钮
  • 管理后台仪表盘:摘要
    Card
    + 筛选栏 +
    Table
  • 实体详情:页头 + 状态
    Badge
    + 主
    Card
    + 侧边
    Card
    + 用于破坏性操作的
    AlertDialog
  • 搜索密集型页面:
    Command
    用于快速查找,
    Popover
    用于选择器,
    Sheet
    用于移动端筛选
  • 认证/引导流程:居中的
    Card
    + 社交登录分隔线
    Separator
    + 内联
    Alert
    显示错误
  • 破坏性操作流程:使用
    AlertDialog
    (而非
    Dialog
    )进行确认

Anti-patterns to avoid

需要避免的反模式

  • Raw
    button
    /
    input
    /
    select
    /
    div
    when shadcn primitives exist
  • Repeated
    div rounded-xl border p-6
    instead of
    Tabs
    /
    Table
    /
    Sheet
    /
    Dialog
  • Multiple accent colors fighting each other
  • Nested cards inside cards inside cards
  • Large gradient backgrounds and glassmorphism on every surface
  • Mixing arbitrary spacing and radius values
  • Using
    Dialog
    for destructive confirmation instead of
    AlertDialog
  • Shipping empty/loading/error states without design treatment
  • Using ad-hoc Tailwind palette classes for foundational surfaces instead of theme tokens
  • 当shadcn基础组件存在时,仍使用原生
    button
    /
    input
    /
    select
    /
    div
  • 重复使用
    div rounded-xl border p-6
    而非
    Tabs
    /
    Table
    /
    Sheet
    /
    Dialog
  • 多种强调色相互冲突
  • 卡片嵌套多层
  • 每个界面都使用大渐变背景和玻璃态效果
  • 混合使用随机的间距和圆角值
  • 使用
    Dialog
    进行破坏性操作确认而非
    AlertDialog
  • 空状态/加载状态/错误状态未经过设计就发布
  • 使用Tailwind调色板类构建核心界面而非主题令牌

Building a Custom Registry

构建自定义注册表

Create your own component registry to share across projects:
创建您自己的组件注册表以在多个项目之间共享:

Registry Types (CLI v4)

注册表类型(CLI v4)

TypePurpose
registry:ui
Individual UI components
registry:base
Full design system payload — components, deps, CSS vars, fonts, config
registry:font
Font configuration as a first-class registry item
类型用途
registry:ui
单个UI组件
registry:base
完整的设计系统负载——包含组件、依赖、CSS变量、字体、配置
registry:font
字体配置作为一等注册表项

1. Define registry.json

1. 定义registry.json

json
[
  {
    "name": "my-component",
    "type": "registry:ui",
    "title": "My Component",
    "description": "A custom component",
    "files": [
      {
        "path": "components/my-component.tsx",
        "type": "registry:ui"
      }
    ],
    "dependencies": ["lucide-react"]
  }
]
json
[
  {
    "name": "my-component",
    "type": "registry:ui",
    "title": "My Component",
    "description": "A custom component",
    "files": [
      {
        "path": "components/my-component.tsx",
        "type": "registry:ui"
      }
    ],
    "dependencies": ["lucide-react"]
  }
]

2. Build

2. 构建

bash
npx shadcn@latest build
bash
npx shadcn@latest build

Outputs to public/r/my-component.json

输出到public/r/my-component.json

undefined
undefined

3. Consume

3. 使用

bash
npx shadcn@latest add https://your-domain.com/r/my-component.json
bash
npx shadcn@latest add https://your-domain.com/r/my-component.json

Component Gotchas

组件常见问题

shadcn init
Breaks Geist Font in Next.js (Tailwind v4)

Next.js中
shadcn init
破坏Geist字体(Tailwind v4)

shadcn init
rewrites
globals.css
and may introduce
--font-sans: var(--font-sans)
— a circular self-reference that breaks font loading. Tailwind v4's
@theme inline
resolves CSS custom properties at parse time, not runtime — so even
var(--font-geist-sans)
won't work because Next.js injects that variable via className at runtime.
The fix: Use literal font family names in
@theme inline
:
css
/* In @theme inline — CORRECT (literal names) */
--font-sans: "Geist", "Geist Fallback", ui-sans-serif, system-ui, sans-serif;
--font-mono: "Geist Mono", "Geist Mono Fallback", ui-monospace, monospace;

/* WRONG — circular, resolves to nothing */
--font-sans: var(--font-sans);

/* ALSO WRONG — @theme inline can't resolve runtime CSS variables */
--font-sans: var(--font-geist-sans);
After running
shadcn init
, always:
  1. Replace font declarations in
    @theme inline
    with literal Geist font names (as shown above)
  2. Move the font variable classNames from
    <body>
    to
    <html>
    in
    layout.tsx
    :
tsx
// layout.tsx — font variables on <html>, not <body>
<html lang="en" className={`${geistSans.variable} ${geistMono.variable}`}>
  <body className="antialiased">
shadcn init
会重写
globals.css
,可能会引入
--font-sans: var(--font-sans)
——这种循环引用会导致字体加载失败。Tailwind v4的
@theme inline
会在解析时解析CSS自定义属性,而非运行时——因此即使使用
var(--font-geist-sans)
也无法生效,因为Next.js是通过className在运行时注入该变量的。
修复方案:在
@theme inline
中使用字面量字体名称:
css
/* 在@theme inline中——正确写法(字面量名称) */
--font-sans: "Geist", "Geist Fallback", ui-sans-serif, system-ui, sans-serif;
--font-mono: "Geist Mono", "Geist Mono Fallback", ui-monospace, monospace;

/* 错误写法——循环引用,解析为空 */
--font-sans: var(--font-sans);

/* 同样错误——@theme inline无法解析运行时CSS变量 */
--font-sans: var(--font-geist-sans);
运行
shadcn init
,请务必:
  1. @theme inline
    中的字体声明替换为字面量Geist字体名称(如上所示)
  2. 将字体变量的className从
    <body>
    移动到
    layout.tsx
    中的
    <html>
    标签:
tsx
// layout.tsx —— 字体变量添加到<html>而非<body>
<html lang="en" className={`${geistSans.variable} ${geistMono.variable}`}>
  <body className="antialiased">

Avatar Has No
size
Prop

Avatar组件没有
size
属性

The shadcn Avatar component does not accept a
size
variant prop. Control size with Tailwind classes:
tsx
// WRONG — no size variant exists
<Avatar size="lg" />  // ❌ TypeScript error / silently ignored

// CORRECT — use Tailwind
<Avatar className="h-12 w-12">
  <AvatarImage src={user.image} />
  <AvatarFallback>JD</AvatarFallback>
</Avatar>

// Small avatar
<Avatar className="h-6 w-6"> ... </Avatar>
This applies to most shadcn components — they use Tailwind classes for sizing, not variant props. If you need reusable size variants, add them yourself via
cva
in the component source.
shadcn的Avatar组件不支持
size
变体属性。请使用Tailwind类来控制尺寸:
tsx
// 错误写法——不存在size变体
<Avatar size="lg" />  // ❌ TypeScript错误/被静默忽略

// 正确写法——使用Tailwind类
<Avatar className="h-12 w-12">
  <AvatarImage src={user.image} />
  <AvatarFallback>JD</AvatarFallback>
</Avatar>

// 小型头像
<Avatar className="h-6 w-6"> ... </Avatar>
这适用于大多数shadcn组件——它们使用Tailwind类来控制尺寸,而非变体属性。如果您需要可复用的尺寸变体,可以在组件源代码中通过
cva
自行添加。

Common Patterns

使用TooltipProvider包裹根组件

cn() Utility

All shadcn components use the
cn()
utility for conditional class merging:
ts
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}
许多组件需要在根节点使用
TooltipProvider
tsx
// app/layout.tsx
import { TooltipProvider } from '@/components/ui/tooltip'

export default function RootLayout({ children }) {
  return (
    <html lang="en" className="dark">
      <body>
        <TooltipProvider>{children}</TooltipProvider>
      </body>
    </html>
  )
}

Extending Components

框架支持

Since you own the source code, extend components directly:
tsx
// components/ui/button.tsx — add your custom variant
const buttonVariants = cva('...', {
  variants: {
    variant: {
      default: '...',
      destructive: '...',
      // Add custom variants
      success: 'bg-green-600 text-white hover:bg-green-700',
      premium: 'bg-gradient-to-r from-purple-500 to-pink-500 text-white',
    },
  },
})
  • Next.js —— 完全支持(App Router + Pages Router)
  • Vite —— 完全支持
  • React Router —— 完全支持
  • Astro —— 完全支持
  • Laravel —— 完全支持(通过Inertia)
  • TanStack Start —— 完全支持

Wrapping with TooltipProvider

预设(CLI v4)

Many components require
TooltipProvider
at the root:
tsx
// app/layout.tsx
import { TooltipProvider } from '@/components/ui/tooltip'

export default function RootLayout({ children }) {
  return (
    <html lang="en" className="dark">
      <body>
        <TooltipProvider>{children}</TooltipProvider>
      </body>
    </html>
  )
}
预设将您的整个设计系统配置(颜色、主题、图标库、字体、圆角)打包为单个共享代码。只需一个字符串即可完成所有配置:
bash
undefined

Framework Support

初始化时应用预设

  • Next.js — Full support (App Router + Pages Router)
  • Vite — Full support
  • React Router — Full support
  • Astro — Full support
  • Laravel — Full support (via Inertia)
  • TanStack Start — Full support
npx shadcn@latest init --preset <code>

Presets (CLI v4)

在现有项目中切换预设(会重新配置所有内容,包括组件)

Presets bundle your entire design system config (colors, theme, icon library, fonts, radius) into a single shareable code. One string configures everything:
bash
undefined
npx shadcn@latest init --preset <code>

在`shadcn/create`上构建自定义预设——发布前可预览颜色、字体和圆角在真实组件上的效果。

Apply a preset during init

RTL支持(2026年)

npx shadcn@latest init --preset <code>
CLI会在安装时自动处理RTL转换:
bash
npx shadcn@latest migrate rtl
自动将方向类(
ml-4
left-2
)转换为逻辑属性(
ms-4
start-2
)。

Switch presets in an existing project (reconfigures everything including components)

官方文档

npx shadcn@latest init --preset <code>

Build custom presets on `shadcn/create` — preview how colors, fonts, and radius apply to real components before publishing.

RTL Support (2026)

The CLI handles RTL transformation at install time:
bash
npx shadcn@latest migrate rtl
Converts directional classes (
ml-4
,
left-2
) to logical properties (
ms-4
,
start-2
) automatically.

Official Documentation