📦 一、初始化 Next.js 项目
打开终端,运行以下命令:
npx create-next-app@latest my-web-app
选择选项:
- TypeScript:Yes ✅(推荐)
- Tailwind CSS:Yes ✅(自动配置)
- App Router:Yes ✅(使用
/app目录) - src directory:Yes ✅(使用
/src) - ESLint、Prettier:Yes ✅
进入项目目录并运行:
cd my-web-app
npm run dev
📁 二、项目结构(使用 App Router)
my-web-app/
├── src/
│ ├── app/
│ │ ├── page.tsx # 首页
│ │ ├── about/
│ │ │ └── page.tsx # 关于页
│ │ └── contact/
│ │ └── page.tsx # 联系页
│ ├── components/ # 公共组件
│ └── styles/ # 样式
├── public/
└── tailwind.config.js
✨ 三、编写代码 Demo
1. ✅ 首页:src/app/page.tsx
export default function Home() {
return (
<main className="text-center p-10">
<h1 className="text-4xl font-bold text-blue-600">欢迎来到我的网站</h1>
<p className="mt-4 text-gray-500">使用 Next.js + Tailwind 构建现代化 Web 应用</p>
</main>
);
}
2. ℹ️ 关于我们页:src/app/about/page.tsx
export default function AboutPage() {
return (
<main className="max-w-3xl mx-auto p-10">
<h2 className="text-3xl font-semibold mb-4">关于我们</h2>
<p>我们是一家专注于 Web 开发的技术团队,致力于提供高质量解决方案。</p>
</main>
);
}
3. 📬 联系我们页:src/app/contact/page.tsx
export default function ContactPage() {
return (
<main className="max-w-xl mx-auto p-10">
<h2 className="text-3xl font-semibold mb-4">联系我们</h2>
<form className="flex flex-col gap-4">
<input type="text" placeholder="姓名" className="border p-2 rounded" />
<input type="email" placeholder="邮箱" className="border p-2 rounded" />
<textarea placeholder="留言信息" className="border p-2 rounded h-24" />
<button className="bg-blue-600 text-white py-2 px-4 rounded hover:bg-blue-700">提交</button>
</form>
</main>
);
}
🧩 四、添加导航栏组件
src/components/Navbar.tsx
'use client'
import Link from 'next/link'
import { usePathname } from 'next/navigation'
export default function Navbar() {
const pathname = usePathname();
const linkStyle = (path: string) =>
`px-4 py-2 rounded ${pathname === path ? 'bg-blue-600 text-white' : 'text-blue-600 hover:bg-blue-100'}`;
return (
<nav className="flex justify-center space-x-4 p-4 shadow sticky top-0 bg-white z-50">
<Link href="/" className={linkStyle('/')}>首页</Link>
<Link href="/about" className={linkStyle('/about')}>关于</Link>
<Link href="/contact" className={linkStyle('/contact')}>联系</Link>
</nav>
)
}
🧱 五、全局布局:src/app/layout.tsx
import './globals.css'
import type { Metadata } from 'next'
import { ReactNode } from 'react'
import Navbar from '@/components/Navbar'
export const metadata: Metadata = {
title: '我的 Web 应用',
description: '由 Next.js 和 Tailwind CSS 驱动',
}
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="zh">
<body className="min-h-screen bg-gray-50">
<Navbar />
{children}
</body>
</html>
)
}
💅 六、添加样式支持(Tailwind)
确保 Tailwind 已配置成功。
src/app/globals.css 内容应包括:
@tailwind base;
@tailwind components;
@tailwind utilities;
🚀 七、本地运行
npm run dev
访问:
🌐 八、部署到 Vercel(推荐)
npx vercel
跟随提示,几分钟内即可上线。
✅ 九、扩展建议
- 添加博客系统(MDX)
- 接入 CMS(如 Sanity 或 Strapi)
- 添加动态页面(如产品详情页)
- 集成数据库(Prisma + PostgreSQL)