shadcn
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseshadcn/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: is interactive by default. Always use (defaults) for non-interactive initialization:
shadcn init-dbash
undefined重要提示:默认情况下是交互式的。请始终使用(默认配置)参数进行非交互式初始化:
shadcn init-dbash
undefinedNon-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 -dOptions:
- — Use default configuration, skip all interactive prompts (REQUIRED for CI/agent use)
-d, --defaults - — Skip confirmation prompts (does NOT skip library selection — use
-y, --yesinstead)-d - — Force overwrite existing configuration
-f, --force - — Scaffold full project template (
-t, --template,next,vite,react-router,astro,laravel)tanstack-start - — Apply a design system preset (colors, theme, icons, fonts, radius) as a single shareable code
--preset - — Choose primitive library:
--base(default) orradixbase-ui - — Set up a monorepo structure
--monorepo
WARNING:/-yalone does NOT make init fully non-interactive — it still prompts for component library selection. Always use--yesto skip ALL prompts.-d
Deprecated in CLI v4:,--style,--base-color,--src-dir, and--no-base-styleflags are removed and will error. The--css-variablesandregistry:buildregistry types are also deprecated. Useregistry:mcpandregistry:baseinstead.registry:font
The init command:
- Detects your framework (Next.js, Vite, React Router, Astro, Laravel, TanStack Start)
- Installs required dependencies (Radix UI, tailwind-merge, class-variance-authority)
- Creates configuration
components.json - Sets up the utility function
cn() - 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选项说明:
- —— 使用默认配置,跳过所有交互式提示(CI/代理场景必填)
-d, --defaults - —— 跳过确认提示(不会跳过库选择——请使用
-y, --yes替代)-d - —— 强制覆盖现有配置
-f, --force - —— 搭建完整项目模板(可选值:
-t, --template,next,vite,react-router,astro,laravel)tanstack-start - —— 应用设计系统预设(包含颜色、主题、图标、字体、圆角),通过单个共享代码实现
--preset - —— 选择基础组件库:
--base(默认)或radixbase-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
初始化命令会执行以下操作:
- 检测您的框架(Next.js、Vite、React Router、Astro、Laravel、TanStack Start)
- 安装所需依赖(Radix UI、tailwind-merge、class-variance-authority)
- 创建配置文件
components.json - 设置工具函数
cn() - 配置用于主题的CSS变量
Add Components
添加组件
bash
undefinedbash
undefinedAdd 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注册表添加
npx shadcn@latest add https://elements.ai-sdk.dev/api/registry/all.json
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 inlinenpx shadcn@latest add https://elements.ai-sdk.dev/api/registry/all.json
选项说明:
- `-o, --overwrite` —— 覆盖现有文件
- `-p, --path` —— 自定义安装路径
- `-a, --all` —— 安装所有组件
- `--dry-run` —— 预览将添加的内容但不写入文件
- `--diff` —— 更新现有组件时显示变更差异
- `--view` —— 内联显示注册表项的源代码Search & List
搜索与列出
bash
npx shadcn@latest search button
npx shadcn@latest list @v0bash
npx shadcn@latest search button
npx shadcn@latest list @v0Build (Custom Registry)
构建(自定义注册表)
bash
npx shadcn@latest build
npx shadcn@latest build ./registry.json -o ./public/rbash
npx shadcn@latest build
npx shadcn@latest build ./registry.json -o ./public/rView, Info & Docs (CLI v4)
查看、信息与文档(CLI v4)
bash
undefinedbash
undefinedView 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 changesbash
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
undefinednpx shadcn@latest migrate radix src/components/custom
undefinedshadcn/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/uishadcn/skills为编码代理提供正确使用组件和注册表所需的上下文信息。它涵盖Radix和Base UI基础组件、更新后的API、组件模式以及注册表工作流程。该技能知道如何使用CLI、何时调用CLI以及传递哪些参数——确保代理生成的代码与您的设计系统匹配。
安装命令:
pnpm dlx skills add shadcn/uiUnified Radix UI Package (February 2026)
统一Radix UI包(2026年2月)
The style now uses a single package instead of individual packages:
new-yorkradix-ui@radix-ui/react-*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: . After migration, remove unused packages from .
npx shadcn@latest migrate radix@radix-ui/react-*package.jsonnew-yorkradix-ui@radix-ui/react-*tsx
// 旧方式——独立包
import * as DialogPrimitive from "@radix-ui/react-dialog"
// 新方式——统一包
import { Dialog as DialogPrimitive } from "radix-ui"迁移现有项目:执行。迁移完成后,从中移除未使用的包。
npx shadcn@latest migrate radixpackage.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-uiThe CLI pulls the correct component variant based on your project configuration automatically.
shadcn/ui现在支持Base UI作为Radix UI之外的另一种基础组件库选项。无论您选择哪种库,组件的外观和行为都保持一致——仅底层实现会有所不同。
初始化时选择:
npx shadcn@latest init --base base-uiCLI会根据您的项目配置自动拉取正确的组件变体。
Configuration (components.json)
配置(components.json)
The file configures how shadcn/ui works in your project:
components.jsonjson
{
"$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.jsonjson
{
"$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-formTheming
主题配置
CSS Variables
CSS变量
shadcn/ui uses CSS custom properties for theming, defined in :
globals.csscss
@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.csscss
@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 class on :
dark<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>darktsx
// 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
最常用组件
| Component | Use Case |
|---|---|
| Actions, form submission |
| Content containers |
| Modals, confirmation prompts |
| Form fields |
| Dropdowns |
| Data display |
| View switching |
| Command palette (Cmd+K) |
| Context menus |
| Floating content |
| Hover hints |
| Status indicators |
| User profile images |
| Scrollable containers |
| Visual dividers |
| Form labels |
| Slide-out panels |
| Loading placeholders |
| 组件 | 使用场景 |
|---|---|
| 操作按钮、表单提交 |
| 内容容器 |
| 模态框、确认提示 |
| 表单字段 |
| 下拉菜单 |
| 数据展示 |
| 视图切换 |
| 命令面板(Cmd+K) |
| 上下文菜单 |
| 悬浮内容 |
| 悬停提示 |
| 状态指示器 |
| 用户头像 |
| 可滚动容器 |
| 视觉分隔线 |
| 表单标签 |
| 滑出面板 |
| 加载占位符 |
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: for product, dashboard, AI, and admin surfaces.
new-york - 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. Avoid ad-hoc hex values.ring-ring - Keep radius consistent. The default is a strong baseline.
--radius: 0.625rem - Use one density system per page: comfortable (/
gap-6/p-6) or compact (text-sm/gap-4/p-4).text-sm - Keep icons quiet and consistent. Lucide icons at or
h-4 w-4.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 case | Reach for this first | Why |
|---|---|---|
| Settings page | | Clear information grouping with predictable save flows |
| Data dashboard | | Covers summary, status, dense data, and row actions without custom shells |
| CRUD table | | Supports browse, act, edit, and destructive confirmation in a standard pattern |
| Auth screen | | Keeps entry flows focused and gives errors a proper treatment |
| Global search | | Fast keyboard-first discovery with an established interaction model |
| Mobile nav | | Provides a compact navigation shell that adapts cleanly to small screens |
| Detail page | header + | Balances hierarchy, metadata, and supporting content without over-nesting |
| Filters | | Works for persistent desktop filters and collapsible mobile controls |
| Empty/loading/error states | | Gives non-happy paths a designed surface instead of placeholder text |
| 使用场景 | 优先选择的组件组合 | 原因 |
|---|---|---|
| 设置页面 | | 清晰的信息分组,搭配可预测的保存流程 |
| 数据仪表盘 | | 涵盖摘要、状态、高密度数据和行操作,无需自定义外壳 |
| CRUD表格 | | 支持浏览、操作、编辑和破坏性操作确认的标准模式 |
| 认证页面 | | 保持登录流程聚焦,错误提示有规范的展示方式 |
| 全局搜索 | | 基于键盘的快速搜索,采用成熟的交互模型 |
| 移动端导航 | | 提供紧凑的导航外壳,可完美适配小屏幕 |
| 详情页面 | 页头 + | 在层级、元数据和辅助内容之间取得平衡,避免过度嵌套 |
| 筛选功能 | | 适用于桌面端的持久化筛选和移动端的可折叠控制 |
| 空状态/加载状态/错误状态 | | 为非成功状态提供经过设计的界面,而非占位文本 |
Composition recipes
组合示例
- Settings page: +
Tabsper group +Card+ save actionSeparator - Admin dashboard: summary s + filter bar +
CardTable - Entity detail: header + status + main
Badge+ sideCard+Cardfor destructiveAlertDialog - Search-heavy: for quick find,
Commandfor pickers,Popoverfor mobile filtersSheet - Auth/onboarding: centered + social
Card+ inlineSeparatorfor errorsAlert - Destructive flows: (not
AlertDialog) for confirmationDialog
- 设置页面:+ 每组对应一个
Tabs+Card+ 保存操作按钮Separator - 管理后台仪表盘:摘要+ 筛选栏 +
CardTable - 实体详情:页头 + 状态+ 主
Badge+ 侧边Card+ 用于破坏性操作的CardAlertDialog - 搜索密集型页面:用于快速查找,
Command用于选择器,Popover用于移动端筛选Sheet - 认证/引导流程:居中的+ 社交登录分隔线
Card+ 内联Separator显示错误Alert - 破坏性操作流程:使用(而非
AlertDialog)进行确认Dialog
Anti-patterns to avoid
需要避免的反模式
- Raw /
button/input/selectwhen shadcn primitives existdiv - Repeated instead of
div rounded-xl border p-6/Tabs/Table/SheetDialog - 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 for destructive confirmation instead of
DialogAlertDialog - Shipping empty/loading/error states without design treatment
- Using ad-hoc Tailwind palette classes for foundational surfaces instead of theme tokens
- 当shadcn基础组件存在时,仍使用原生/
button/input/selectdiv - 重复使用而非
div rounded-xl border p-6/Tabs/Table/SheetDialog - 多种强调色相互冲突
- 卡片嵌套多层
- 每个界面都使用大渐变背景和玻璃态效果
- 混合使用随机的间距和圆角值
- 使用进行破坏性操作确认而非
DialogAlertDialog - 空状态/加载状态/错误状态未经过设计就发布
- 使用Tailwind调色板类构建核心界面而非主题令牌
Building a Custom Registry
构建自定义注册表
Create your own component registry to share across projects:
创建您自己的组件注册表以在多个项目之间共享:
Registry Types (CLI v4)
注册表类型(CLI v4)
| Type | Purpose |
|---|---|
| Individual UI components |
| Full design system payload — components, deps, CSS vars, fonts, config |
| Font configuration as a first-class registry item |
| 类型 | 用途 |
|---|---|
| 单个UI组件 |
| 完整的设计系统负载——包含组件、依赖、CSS变量、字体、配置 |
| 字体配置作为一等注册表项 |
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 buildbash
npx shadcn@latest buildOutputs to public/r/my-component.json
输出到public/r/my-component.json
undefinedundefined3. Consume
3. 使用
bash
npx shadcn@latest add https://your-domain.com/r/my-component.jsonbash
npx shadcn@latest add https://your-domain.com/r/my-component.jsonComponent Gotchas
组件常见问题
shadcn init
Breaks Geist Font in Next.js (Tailwind v4)
shadcn initNext.js中shadcn init
破坏Geist字体(Tailwind v4)
shadcn initshadcn initglobals.css--font-sans: var(--font-sans)@theme inlinevar(--font-geist-sans)The fix: Use literal font family names in :
@theme inlinecss
/* 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 , always:
shadcn init- Replace font declarations in with literal Geist font names (as shown above)
@theme inline - Move the font variable classNames from to
<body>in<html>:layout.tsx
tsx
// layout.tsx — font variables on <html>, not <body>
<html lang="en" className={`${geistSans.variable} ${geistMono.variable}`}>
<body className="antialiased">shadcn initglobals.css--font-sans: var(--font-sans)@theme inlinevar(--font-geist-sans)修复方案:在中使用字面量字体名称:
@theme inlinecss
/* 在@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- 将中的字体声明替换为字面量Geist字体名称(如上所示)
@theme inline - 将字体变量的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
sizeAvatar组件没有size
属性
sizeThe shadcn Avatar component does not accept a variant prop. Control size with Tailwind classes:
sizetsx
// 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 in the component source.
cvashadcn的Avatar组件不支持变体属性。请使用Tailwind类来控制尺寸:
sizetsx
// 错误写法——不存在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类来控制尺寸,而非变体属性。如果您需要可复用的尺寸变体,可以在组件源代码中通过自行添加。
cvaCommon Patterns
使用TooltipProvider包裹根组件
cn() Utility
—
All shadcn components use the utility for conditional class merging:
cn()ts
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}许多组件需要在根节点使用:
TooltipProvidertsx
// 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 at the root:
TooltipProvidertsx
// 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
undefinedFramework 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
undefinednpx 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-4left-2ms-4start-2Switch 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 rtlConverts directional classes (, ) to logical properties (, ) automatically.
ml-4left-2ms-4start-2—
Official Documentation
—