shadcn-svelte
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseshadcn-svelte
shadcn-svelte
A framework for building UI, components, and design systems for Svelte. Components are added as source to the user's project via the CLI.
IMPORTANT: Run all CLI commands using the project's package runner:,npx shadcn-svelte@latest, orpnpm dlx shadcn-svelte@latest— based on the project's package manager. Examples below usebunx --bun shadcn-svelte@latestbut substitute the correct runner for the project.npx shadcn-svelte@latest
一款为Svelte构建UI、组件和设计系统的框架。组件通过CLI以源码形式添加到用户项目中。
重要提示: 使用项目的包管理器运行所有CLI命令:、npx shadcn-svelte@latest或pnpm dlx shadcn-svelte@latest—— 根据项目使用的包管理器选择。以下示例使用bunx --bun shadcn-svelte@latest,请根据实际情况替换为正确的命令。npx shadcn-svelte@latest
Current Project Context
当前项目上下文
Read at the project root and, when you need the live file layout, list the directory given by the path (resolved with the same rules as the CLI).
components.jsonaliases.ui读取项目根目录下的文件,当需要实时文件结构时,列出路径对应的目录(解析规则与CLI一致)。
components.jsonaliases.uiImports (Svelte)
导入规则(Svelte)
Each component lives in its own folder with an barrel. Match the installation docs:
index.ts- Multi-part components (dialog, select, card, field, tabs, …): then
import * as Dialog from "$lib/components/ui/dialog",Dialog.Content,Dialog.Title,Card.Root, etc. — whatever the barrel exports (short names and/orCard.Headeraliases).Root as … - Single-component barrels (only one meaningful component in the folder): named imports — and
import { Button } from "$lib/components/ui/button", not<Button>+import * as Button. Same pattern forButton.Root,{ Input },{ Badge },{ Spinner },{ Checkbox },{ Separator }, etc.{ Skeleton }
ts
import * as Dialog from "$lib/components/ui/dialog";
import { Button } from "$lib/components/ui/button";
import { Separator } from "$lib/components/ui/separator";Use the real aliases from (often ), not hardcoded paths.
components.json$lib/components/ui/...每个组件都位于独立文件夹中,并包含桶文件。请遵循安装文档:
index.ts- 多部分组件(dialog、select、card、field、tabs等):,然后使用
import * as Dialog from "$lib/components/ui/dialog"、Dialog.Content、Dialog.Title、Card.Root等——即桶文件导出的内容(短名称和/或Card.Header别名)。Root as … - 单组件桶文件(文件夹中仅有一个核心组件):使用命名导入——并以
import { Button } from "$lib/components/ui/button"形式使用,而非<Button>+import * as Button。Button.Root、{ Input }、{ Badge }、{ Spinner }、{ Checkbox }、{ Separator }等组件均遵循此模式。{ Skeleton }
ts
import * as Dialog from "$lib/components/ui/dialog";
import { Button } from "$lib/components/ui/button";
import { Separator } from "$lib/components/ui/separator";使用中的真实别名(通常为),而非硬编码路径。
components.json$lib/components/ui/...Principles
设计原则
- Use existing components first. Run with no arguments to browse available components, or check Components before writing custom UI.
npx shadcn-svelte@latest add - 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-svelte@latest add - 组合而非重造。设置页面 = 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.
class - 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
- 用于布局而非样式。绝不要覆盖组件的颜色或排版。
class - 禁止使用或
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() - 覆盖类组件禁止手动设置。Dialog、Sheet、Popover等组件会自行处理层级堆叠。
z-index
Forms & Inputs → forms.md
表单与输入框 → forms.md
- Forms use +
Field.FieldGroup. Never use rawField.Fieldwithdivorspace-y-*for form layout.grid gap-* - uses
InputGroup/InputGroup.Input. Never rawInputGroup.Textarea/InputinsideTextarea.InputGroup.Root - Buttons inside inputs use +
InputGroup.Root.InputGroup.Addon - Option sets (2–7 choices) use . Don't loop
ToggleGroupwith manual active state.Button - +
Field.FieldSetfor grouping related checkboxes/radios. Don't use aField.FieldLegendwith a heading.div - Field validation uses +
data-invalid.aria-invalidondata-invalid,Fieldon the control. For disabled:aria-invalidondata-disabled,Fieldon the control.disabled
- 表单使用+
Field.FieldGroup。绝不要使用原始Field.Field搭配div或space-y-*进行表单布局。grid gap-* - 使用
InputGroup/InputGroup.Input。绝不要在InputGroup.Textarea中直接使用InputGroup.Root/Input。Textarea - 输入框内的按钮使用+
InputGroup.Root。InputGroup.Addon - 选项集(2-7个选项)使用。不要循环渲染
ToggleGroup并手动管理激活状态。Button - 相关复选框/单选框分组使用+
Field.FieldSet。不要使用带标题的Field.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. →
Select.Item.Select.Group→DropdownMenu.Item.DropdownMenu.Group→Command.Item.Command.Group - Custom triggers. Wrap controls in /
Dialog.Trigger, or control open state withAlertDialog.Triggeron the root — see component docs.bind:open - Dialog, Sheet, and Drawer always need a Title. ,
Dialog.Title,Sheet.Titlerequired for accessibility. UseDrawer.Titleif visually hidden.class="sr-only" - Use full Card composition. /
Card.Header/Card.Title/Card.Description/Card.Content. Don't dump everything inCard.Footer.Card.Content - Button has no /
isPending. Compose withisLoadinginsideSpinner+Button; usedisabled/data-icon="inline-start"oninline-endfor correct spacing (Spinner,import { Button }).import { Spinner } - must be inside
Tabs.Trigger. Never render triggers directly inTabs.List.Tabs - always needs
Avatar. For when the image fails to load.Avatar.Fallback
- 子项必须位于对应Group内。需放在
Select.Item中;Select.Group需放在DropdownMenu.Item中;DropdownMenu.Group需放在Command.Item中。Command.Group - 自定义触发器。将控件包裹在/
Dialog.Trigger中,或在根组件上使用AlertDialog.Trigger控制打开状态——详见组件文档。bind:open - Dialog、Sheet和Drawer必须包含Title。、
Dialog.Title、Sheet.Title是无障碍访问的必填项。若需视觉隐藏,可添加Drawer.Title。class="sr-only" - 完整使用Card组合。使用/
Card.Header/Card.Title/Card.Description/Card.Content。不要将所有内容都放在Card.Footer中。Card.Content - Button无/
isPending属性。在isLoading内组合Button并添加Spinner;在disabled上使用Spinner/data-icon="inline-start"确保间距正确(需导入inline-end和{ Button })。{ Spinner } - 必须放在
Tabs.Trigger内。绝不要直接在Tabs.List中渲染触发器。Tabs - 必须包含
Avatar。用于图片加载失败时的占位。Avatar.Fallback
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
svelte-sonnerfromtoast()with the Sonner component from your UI folder.svelte-sonner - Use instead of
Separatoror a<hr>with border-only classes.div - Use for loading placeholders. No custom
Skeletondivs.animate-pulse - Use instead of custom styled spans.
Badge
- 优先使用现有组件而非自定义标记。在编写带样式的前,先确认是否已有对应组件。
div - 提示框使用。不要构建自定义样式的div。
Alert - 空状态使用。不要构建自定义空状态标记。
Empty - 通知使用。从
svelte-sonner导入svelte-sonner并使用UI文件夹中的Sonner组件。toast() - **使用**替代
Separator或仅含边框类的<hr>。div - 加载占位使用。不要自定义
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 components. Import from the configured (e.g.
iconLibrary), not string keys.@lucide/svelte
- 中的图标使用
<Button>。在图标上添加data-icon或data-icon="inline-start"。data-icon="inline-end" - 组件内的图标不要添加尺寸类。组件会通过CSS处理图标尺寸。不要使用或
size-4。w-4 h-4 - 以组件形式传入图标。从配置的(如
iconLibrary)导入,而非使用字符串键。@lucide/svelte
CLI
CLI
- Presets — copy the encoded string from the design-system builder on shadcn-svelte.com and pass it to .
npx shadcn-svelte@latest init --preset <code>
- 预设 —— 从shadcn-svelte.com的设计系统构建器中复制编码字符串,然后传入命令。
npx shadcn-svelte@latest init --preset <code>
Key Patterns
核心模式
These are the most common patterns that differentiate correct shadcn-svelte code. For edge cases, see the linked rule files above.
svelte
<script lang="ts">
import * as Field from "$lib/components/ui/field";
import { Input } from "$lib/components/ui/input";
import { Button } from "$lib/components/ui/button";
import SearchIcon from "@lucide/svelte/icons/search";
import { Badge } from "$lib/components/ui/badge";
import * as Avatar from "$lib/components/ui/avatar";
</script>
<!-- Form layout: Field.FieldGroup + Field.Field, not div + Label. -->
<Field.FieldGroup>
<Field.Field>
<Field.FieldLabel for="email">Email</Field.FieldLabel>
<Input id="email" />
</Field.Field>
</Field.FieldGroup>
<!-- Validation: data-invalid on Field, aria-invalid on the control. -->
<Field.Field data-invalid>
<Field.FieldLabel for="email">Email</Field.FieldLabel>
<Input id="email" aria-invalid />
<Field.FieldDescription>Invalid email.</Field.FieldDescription>
</Field.Field>
<!-- Icons in buttons: data-icon, no sizing classes. -->
<Button>
<SearchIcon data-icon="inline-start" />
Search
</Button>
<!-- Spacing: gap-*, not space-y-*. -->
<div class="flex flex-col gap-4"></div>
<!-- Equal dimensions: size-*, not w-* h-*. -->
<Avatar.Root class="size-10">
<Avatar.Image src="/u.png" alt="User" />
<Avatar.Fallback>U</Avatar.Fallback>
</Avatar.Root>
<!-- Status colors: Badge variants or semantic tokens, not raw colors. -->
<Badge variant="secondary">+20.1%</Badge>以下是区分shadcn-svelte代码是否规范的最常见模式。如需了解边缘情况,请参阅上述链接的规则文件。
svelte
<script lang="ts">
import * as Field from "$lib/components/ui/field";
import { Input } from "$lib/components/ui/input";
import { Button } from "$lib/components/ui/button";
import SearchIcon from "@lucide/svelte/icons/search";
import { Badge } from "$lib/components/ui/badge";
import * as Avatar from "$lib/components/ui/avatar";
</script>
<!-- 表单布局:使用Field.FieldGroup + Field.Field,而非div + Label。 -->
<Field.FieldGroup>
<Field.Field>
<Field.FieldLabel for="email">邮箱</Field.FieldLabel>
<Input id="email" />
</Field.Field>
</Field.FieldGroup>
<!-- 验证:在Field上添加data-invalid,在控件上添加aria-invalid。 -->
<Field.Field data-invalid>
<Field.FieldLabel for="email">邮箱</Field.FieldLabel>
<Input id="email" aria-invalid />
<Field.FieldDescription>无效邮箱。</Field.FieldDescription>
</Field.Field>
<!-- 按钮中的图标:使用data-icon,不添加尺寸类。 -->
<Button>
<SearchIcon data-icon="inline-start" />
搜索
</Button>
<!-- 间距:使用gap-*,而非space-y-*。 -->
<div class="flex flex-col gap-4"></div>
<!-- 等尺寸:使用size-*,而非w-* h-*。 -->
<Avatar.Root class="size-10">
<Avatar.Image src="/u.png" alt="用户" />
<Avatar.Fallback>U</Avatar.Fallback>
</Avatar.Root>
<!-- 状态颜色:使用Badge变体或语义化令牌,而非原始颜色。 -->
<Badge variant="secondary">+20.1%</Badge>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个选项间切换 | |
| 数据展示 | |
| 导航控件 | |
| 覆盖层组件 | |
| 反馈组件 | |
| 命令面板 | |
| 图表 | |
| 布局组件 | |
| 空状态 | |
| 菜单组件 | |
| 提示/信息弹窗 | |
Key Fields
核心配置字段
Use and the filesystem — not a separate command:
components.jsoninfo- → use the actual alias prefix from config (e.g.
aliases), never hardcode unrelated projects.$lib/ - → the global CSS file where theme variables live. Edit this file for theme tweaks; don't add a second globals file unless the user already uses one.
tailwind.css - → visual treatment (e.g.
style,nova, …) and registry style path.vega - → determines icon packages (
iconLibrary,@lucide/svelte, etc.). Never assume@tabler/icons-svelte.@lucide/svelte - → where the CLI fetches components; default official registry at
registry.shadcn-svelte.com - (conceptual) → the CLI resolves
resolvedPathsto absolute paths; listaliaseson disk to see installed components.aliases.ui
See cli.md for commands and flags.
使用和文件系统——无需单独的命令:
components.jsoninfo- → 使用配置中的实际别名前缀(如
aliases),绝不要硬编码其他项目的路径。$lib/ - → 存储主题变量的全局CSS文件。如需调整主题,请编辑此文件;除非用户已使用其他全局文件,否则不要新增第二个全局文件。
tailwind.css - → 视觉风格(如
style、nova等)及注册表样式路径。vega - → 确定图标包(如
iconLibrary、@lucide/svelte等)。不要默认使用@tabler/icons-svelte。@lucide/svelte - → CLI获取组件的来源;默认官方注册表为
registry。shadcn-svelte.com - (概念性)→ CLI将
resolvedPaths解析为绝对路径;列出磁盘上的aliases路径即可查看已安装组件。aliases.ui
有关命令和参数,请参阅cli.md。
Component Docs, Examples, and Usage
组件文档、示例与使用方法
Open for docs and examples. When creating, fixing, debugging, or using a component, read the official page first so you follow the documented APIs.
https://shadcn-svelte.com/docs/components/<name>.md访问查看文档和示例。在创建、修复、调试或使用组件前,请先阅读官方文档,确保遵循已记录的API。
https://shadcn-svelte.com/docs/components/<name>.mdWorkflow
工作流程
- Get project context — read and list the UI components directory when needed.
components.json - Check installed components first — before running , list files under the resolved
addpath. Don't import components that haven't been added, and don't re-add ones already present unless updating.ui - Discover components — with no arguments (interactive list), or the docs site.
npx shadcn-svelte@latest add - Install or update — or a registry URL. To refresh existing files from the registry, use
npx shadcn-svelte@latest add <name>(see cli.md).npx shadcn-svelte@latest update - Fix imports in third-party / URL-added items — After adding from a custom registry URL, check for hardcoded paths that don't match the project's . Rewrite imports to use the project's
aliases/uialiases fromlib.components.json - Review added components — After adding, read the added files and verify composition (groups, titles, validation attrs). Align icon imports with .
iconLibrary - Remote registry items — Adding by URL is explicit; if the user wants a component from an unknown source, confirm the registry URL or item before running .
add
- 获取项目上下文 —— 读取,必要时列出UI组件目录。
components.json - 优先检查已安装组件 —— 在运行命令前,列出解析后的
add路径下的文件。不要导入未添加的组件,除非需要更新,否则不要重新添加已存在的组件。ui - 发现组件 —— 运行不带参数的(交互式列表),或访问文档网站。
npx shadcn-svelte@latest add - 安装或更新 —— 运行或指定注册表URL。如需从注册表刷新现有文件,使用
npx shadcn-svelte@latest add <name>(详见cli.md)。npx shadcn-svelte@latest update - 修复第三方/URL添加组件的导入 —— 从自定义注册表URL添加组件后,检查是否存在与项目不匹配的硬编码路径。将导入重写为使用项目
aliases中的components.json/ui别名。lib - 审核添加的组件 —— 添加完成后,读取添加的文件并验证组合方式(分组、标题、验证属性)。确保图标导入与一致。
iconLibrary - 远程注册表组件 —— 通过URL添加组件需明确操作;若用户需要来自未知源的组件,在运行前请确认注册表URL或组件信息。
add
Updating Components
更新组件
Use the command to pull the latest registry versions of components already in the project. Review changes with after .
updategit diffupdate- Commit or stash local work.
- Run or
npx shadcn-svelte@latest update [component].--all - Resolve merge conflicts if you had customized files.
- Never use on
--overwritewithout the user's explicit approval when it would destroy intentional edits.add
使用****命令拉取项目中已安装组件的最新注册表版本。更新后使用查看变更。
updategit diff- 提交或暂存本地修改。
- 运行或
npx shadcn-svelte@latest update [component]。--all - 若文件已自定义,解决合并冲突。
- 未经用户明确许可,绝不要在命令中使用
add,否则会覆盖用户的有意修改。--overwrite
Quick Reference
快速参考
bash
undefinedbash
undefinedInitialize shadcn-svelte in your project.
在项目中初始化shadcn-svelte。
npx shadcn-svelte@latest init
npx shadcn-svelte@latest init
Initialize with a preset string from the docs site builder.
使用文档网站构建器中的预设字符串初始化。
npx shadcn-svelte@latest init --preset <code>
npx shadcn-svelte@latest init --preset <code>
Add components (interactive when run with no names).
添加组件(不带参数时为交互式列表)。
npx shadcn-svelte@latest add
npx shadcn-svelte@latest add button card dialog
npx shadcn-svelte@latest add --all
npx shadcn-svelte@latest add
npx shadcn-svelte@latest add button card dialog
npx shadcn-svelte@latest add --all
Update components already installed.
更新已安装的组件。
npx shadcn-svelte@latest update button
npx shadcn-svelte@latest update --all --yes
npx shadcn-svelte@latest update button
npx shadcn-svelte@latest update --all --yes
Build a custom registry (registry authors).
构建自定义注册表(注册表作者使用)。
npx shadcn-svelte@latest registry build
**Registry:** default `https://shadcn-svelte.com/registry` — override in `components.json` if needed.
**Docs:** [shadcn-svelte.com](https://shadcn-svelte.com)npx shadcn-svelte@latest registry build
**注册表:** 默认地址为`https://shadcn-svelte.com/registry`——如需修改,可在`components.json`中配置。
**文档:** [shadcn-svelte.com](https://shadcn-svelte.com)Detailed References
详细参考
- rules/forms.md — Field.FieldGroup, Field.Field, InputGroup, ToggleGroup, Field.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 icon components
- rules/styling.md — Semantic colors, variants, class, spacing, size, truncate, dark mode, cn(), z-index
- cli.md — Commands, flags, registry
- customization.md — Theming, CSS variables, extending components
- rules/forms.md —— Field.FieldGroup、Field.Field、InputGroup、ToggleGroup、Field.FieldSet、验证状态
- rules/composition.md —— 分组、覆盖层、Card、Tabs、Avatar、Alert、Empty、Toast、Separator、Skeleton、Badge、Button加载状态
- rules/icons.md —— data-icon、图标尺寸、传入图标组件
- rules/styling.md —— 语义化颜色、变体、class、间距、size、truncate、深色模式、cn()、z-index
- cli.md —— 命令、参数、注册表
- customization.md —— 主题定制、CSS变量、组件扩展