shadcn/ui 组件库
shadcn/ui是一套当下非常流行的React组件库,与传统组件库不同,它采用了一种独特的"复制粘贴"模式,组件代码直接存放在项目中供开发者自由修改。shadcn/ui基于Radix UI无样式组件和Tailwind CSS构建,提供了一系列设计精美、可访问性良好的UI组件,在React社区中非常流行,在Github上高达106K星。
Github地址:https://github.com/shadcn-ui/ui
和传统组件库的区别
传统组件库如Ant Design等,它们通过npm包的形式分发,开发者无法直接修改组件源码,只能通过预留的API进行定制。这种模式虽然使用便捷,但遇到深度定制需求时往往束手无策,不得不通过覆盖样式、hack代码等方式强行实现效果,因此这类组件库主要适用于企业级中后台项目,非常不适合C端(前台)项目。
shadcn/ui则采用了完全不同的思路,它不是一个npm包,而是通过CLI工具将组件源码直接复制到项目中,开发者拥有组件的完整控制权,我们可以根据业务需求自由修改任何细节。这种方式的优势在于灵活性极高,劣势则是组件更新需要手动处理,且对开发者的能力要求更高。
搭建项目并引入shadcn/ui
使用shadcn/ui需要先初始化一个React项目,官方推荐使用Next.js、Vite等现代化构建工具,这里我们以Vite为例进行演示。首先创建一个Vite + React + TypeScript项目。
npm create vite@latest .
然后安装并配置Tailwind CSS v4。
npm i tailwindcss @tailwindcss/vite
修改vite.config.ts,添加Tailwind CSS插件。
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [react(), tailwindcss()],
});
修改src/index.css,引入Tailwind CSS。
@import "tailwindcss";
配置路径别名,修改tsconfig.json。
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
修改vite.config.ts添加别名配置。
import path from "path";
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
最后运行shadcn/ui初始化命令。
npx shadcn@latest init
初始化过程中,如果前面项目有步骤配置的不对通常会抛出错误,根据提示对应修复即可,此外还会询问一些配置选项,包括样式主题、CSS变量等,根据项目需求选择即可。初始化完成后,项目中会生成components.json配置文件和src/components/ui目录用于存放组件。
添加和使用组件
shadcn/ui提供了丰富的组件,包括Button、Card、Dialog、Form、Table等常用UI组件。添加组件非常简单,使用CLI命令即可,下面例子我们添加一个按钮组件。
npx shadcn@latest add button
执行后,Button组件的源码会被复制到src/components/ui/button.tsx,我们可以直接在项目中使用。
import { Button } from "@/components/ui/button";
const App = () => {
return (
<div className="p-4">
<Button>默认按钮</Button>
<Button variant="destructive">危险按钮</Button>
<Button variant="outline">边框按钮</Button>
<Button variant="ghost">幽灵按钮</Button>
</div>
);
};
export default App;
如果需要查看所有可用组件,可以访问官方文档或执行命令查看。
npx shadcn@latest add
组件定制
由于组件源码直接存放在项目中,我们可以根据业务需求自由修改。例如修改Button组件添加新的变体。
const buttonVariants = cva(
"inline-flex items-center justify-center ...",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive: "bg-destructive text-destructive-foreground ...",
// 添加自定义变体
success: "bg-green-500 text-white hover:bg-green-600",
},
// ...
},
}
);
这种灵活性是传统组件库难以实现的,因此shadcn/ui非常适合设计灵活多变的C端项目。