Docs
Next.js
Next.js
安装和配置 Next.js。
创建项目
使用create-next-app
创建一个新的 Next.js 项目
npx create-next-app@latest my-app --typescript --tailwind --eslint
运行 CLI
运行 shadcn-ui
init 初始化项目:
npx shadcn-ui@latest init
配置 components.json
系统将询问您几个问题来配置 components.json
:
Which style would you like to use? › Default
Which color would you like to use as base color? › Slate
Do you want to use CSS variables for colors? › no / yes
字体
我使用 Inter 作为默认字体,Inter 不是必选项。您可以将其替换为任何其他字体。
以下是我为 Next.js 配置 Inter 字体的方式:
1. 导入 Root Layout 中的字体:
import "@/styles/globals.css"
import { Inter as FontSans } from "next/font/google"
import { cn } from "@/lib/utils"
const fontSans = FontSans({
subsets: ["latin"],
variable: "--font-sans",
})
export default function RootLayout({ children }: RootLayoutProps) {
return (
<html lang="en" suppressHydrationWarning>
<head />
<body
className={cn(
"min-h-screen bg-background font-sans antialiased",
fontSans.variable
)}
>
...
</body>
</html>
)
}
2. 配置 theme.extend.fontFamily
in tailwind.config.js
const { fontFamily } = require("tailwindcss/defaultTheme")
/** @type {import('tailwindcss').Config} */
module.exports = {
darkMode: ["class"],
content: ["app/**/*.{ts,tsx}", "components/**/*.{ts,tsx}"],
theme: {
extend: {
fontFamily: {
sans: ["var(--font-sans)", ...fontFamily.sans],
},
},
},
}
目录结构
以下是我构建 Next.js 应用程序的目录结构。可以将此用作参考:
.
├── app
│ ├── layout.tsx
│ └── page.tsx
├── components
│ ├── ui
│ │ ├── alert-dialog.tsx
│ │ ├── button.tsx
│ │ ├── dropdown-menu.tsx
│ │ └── ...
│ ├── main-nav.tsx
│ ├── page-header.tsx
│ └── ...
├── lib
│ └── utils.ts
├── styles
│ └── globals.css
├── next.config.js
├── package.json
├── postcss.config.js
├── tailwind.config.js
└── tsconfig.json
- 我将 UI 组件放在
components/ui
文件夹。 - 其余组件例如
<PageHeader />
and<MainNav />
放在components
文件夹中。 lib
文件夹包含全部的工具函数,在一个utils.ts
文件定义了cn
帮助函数。styles
文件夹包含了全局样式 global CSS.
就是这样
现在,可以开始向项目添加组件。
npx shadcn-ui@latest add button
上面的命令会将 Button
组件添加到项目中,然后可以像这样导入它:
import { Button } from "@/components/ui/button"
export default function Home() {
return (
<div>
<Button>Click me</Button>
</div>
)
}