shadcn/ui 组件库

shadcn/ui 的核心理念:源码复制而非 npm 依赖、组件变体设计、与 Tailwind CSS 的配合、定制自由度。

#type / resource #status / growing #tech / dev / frontend #resource / react

[!info] related notes

shadcn/ui 组件库

核心理念

传统组件库(Ant Design、Material UI)通过 npm install 引入打包后的 JS。shadcn/ui 反其道:把组件源码复制到你的项目里

好处:

  • 源码就是你的代码,随意改
  • 只包含你实际使用的组件
  • 没有版本升级破坏自定义的风险
  • 不增加 node_modules 依赖

使用方式

npx shadcn add button   # 把 Button 源码复制到 components/ui/button.tsx
npx shadcn add card
npx shadcn add input

组件变体

class-variance-authority (cva) 定义变体:

const buttonVariants = cva("inline-flex items-center ...", {
  variants: {
    variant: {
      default: "bg-primary text-primary-foreground",
      destructive: "bg-destructive text-destructive-foreground",
      outline: "border border-input",
      ghost: "hover:bg-accent",
    },
    size: {
      default: "h-10 px-4 py-2",
      sm: "h-9 px-3",
      lg: "h-11 px-8",
    },
  },
});

与 Tailwind CSS 4.x 配合

Tailwind CSS 4.x 用 CSS-first 配置:

@theme {
  --color-primary: oklch(0.65 0.24 275);
  --radius-md: 0.5rem;
}

shadcn/ui 组件用这些 CSS 变量,改 @theme 就能全局换肤。

定制

组件源码在你的项目里,直接改:

// components/ui/button.tsx
// 改默认样式、加新变体、调整布局,随意

与 Ant Design 的对比

维度shadcn/uiAnt Design
安装方式复制源码npm install
定制直接改源码主题 token
包体积只有使用的tree-shaking
设计语言中性Ant Design 风格

需要高度定制的 UI 选 shadcn/ui;快速出页面选 Ant Design。

创建于 2026/6/25 更新于 2026/6/25