组件
创建项目
首先使用 vite
创建一个新的 React 项目。选择 React + TypeScript 模板。
pnpm create vite@latest
添加 Tailwind CSS
pnpm add tailwindcss @tailwindcss/vite
将 src/index.css
中的所有内容替换为以下代码:
@import "tailwindcss";
编辑 tsconfig.json 文件
当前版本的 Vite 将 TypeScript 配置拆分为三个文件,其中两个需要编辑。将 baseUrl
和 paths
属性添加到 tsconfig.json
和 tsconfig.app.json
文件的 compilerOptions
部分:
{
"files": [],
"references": [
{
"path": "./tsconfig.app.json"
},
{
"path": "./tsconfig.node.json"
}
],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
编辑 tsconfig.app.json 文件
将以下代码添加到 tsconfig.app.json
文件中,以解决 IDE 的路径问题:
{
"compilerOptions": {
// ...
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
// ...
}
}
更新 vite.config.ts
将以下代码添加到 vite.config.ts,以便您的应用可以正确解析路径:
pnpm add -D @types/node
import path from "path"
import tailwindcss from "@tailwindcss/vite"
import react from "@vitejs/plugin-react"
import { defineConfig } from "vite"
// https://vite.ac.cn/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
})
运行 CLI
运行 shadcn
init 命令来设置您的项目:
pnpm dlx shadcn@latest init
系统会询问您几个问题来配置 components.json
。
Which color would you like to use as base color? › Neutral
添加组件
现在您可以开始向项目中添加组件了。
pnpm dlx shadcn@latest add button
上述命令会将 Button
组件添加到您的项目中。然后您可以像这样导入它:
import { Button } from "@/components/ui/button"
function App() {
return (
<div className="flex min-h-svh flex-col items-center justify-center">
<Button>Click me</Button>
</div>
)
}
export default App