Next.js入门指南:从零构建现代Web应用

Next.js 是一个用于构建全栈 Web 应用程序的 React 框架。它提供了服务端渲染(SSR)、静态站点生成(SSG)、路由系统等开箱即用的特性,让开发者能够专注于业务逻辑的实现。

1. 什么是 Next.js?

Next.js 被称为 “The React Framework for the Web”。它解决了纯 React 应用在 SEO、首屏加载速度和路由配置上的痛点。

主要特性包括:

  • 混合渲染:支持服务器端渲染 (SSR) 和 静态生成 (SSG)。
  • 路由系统:基于文件系统的路由(App Router)。
  • 全栈能力:支持 API Routes,可直接编写后端逻辑。
  • 自动优化:图片、字体和脚本的自动优化。

2. 环境准备

在开始之前,请确保你的系统已安装 Node.js(建议 v18.17 或更高版本)。

1
node -v

3. 创建项目

我们将使用官方脚手架 create-next-app 来创建一个新项目。打开终端,运行以下命令:

1
npx create-next-app@latest my-next-app

在安装过程中,你可能会遇到以下提示,建议选择如下配置:

1
2
3
4
5
6
Would you like to use TypeScript?  Yes
Would you like to use ESLint? Yes
Would you like to use Tailwind CSS? Yes
Would you like to use `src/` directory? Yes
Would you like to use App Router? (recommended) Yes
Would you like to customize the default import alias (@/*)? No

项目创建完成后,生成的目录结构大致如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
my-next-app/
├── public/ # 静态资源(图片、字体等)
├── src/
│ └── app/ # 应用路由和页面
│ ├── globals.css
│ ├── layout.tsx
│ └── page.tsx
├── .eslintrc.json # ESLint 配置
├── next.config.js # Next.js 配置
├── package.json # 项目依赖和脚本
├── postcss.config.js # PostCSS 配置
├── tailwind.config.ts # Tailwind CSS 配置
└── tsconfig.json # TypeScript 配置

安装完成后,进入项目目录并启动开发服务器:

1
2
cd my-next-app
npm run dev

访问 http://localhost:3000,你应该能看到 Next.js 的欢迎页面。

4. 实战:创建你的第一个页面

在 Next.js 的 App Router 模式中,app 目录下的文件夹结构即对应路由结构。

创建关于页面

  1. src/app 目录下创建一个名为 about 的文件夹。
  2. about 文件夹中创建一个 page.tsx 文件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/app/about/page.tsx
import Link from 'next/link';

export default function About() {
return (
<div className="flex min-h-screen flex-col items-center justify-between p-24">
<h1 className="text-4xl font-bold">关于我们</h1>
<p className="mt-4">这是一个使用 Next.js 构建的示例页面。</p>

<div className="mt-8">
<Link href="/" className="text-blue-500 hover:underline">
返回首页
</Link>
</div>
</div>
);
}

现在访问 http://localhost:3000/about,你就能看到刚才创建的页面了。Next.js 自动为你处理了路由映射。

5. 组件与布局

Next.js 使用 layout.tsx 来定义共享布局。根目录下的 app/layout.tsx 是全局布局,适用于所有页面。

你可以修改 src/app/layout.tsx 来添加全局导航栏:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Link from "next/link";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
title: "我的 Next.js 应用",
description: "Generated by create next app",
};

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="zh-CN">
<body className={inter.className}>
<nav className="p-4 bg-gray-100 border-b">
<ul className="flex gap-4">
<li><Link href="/">首页</Link></li>
<li><Link href="/about">关于</Link></li>
</ul>
</nav>
{children}
</body>
</html>
);
}

这样,导航栏就会出现在应用的所有页面上。

6. 数据获取

Next.js 简化了数据获取流程。在 App Router 中,你可以直接在组件中进行异步数据获取(因为组件默认是 Server Components)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/app/posts/page.tsx

async function getData() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
}

export default async function Posts() {
const posts = await getData();

return (
<div className="p-24">
<h1 className="text-2xl font-bold mb-4">文章列表</h1>
<ul>
{posts.slice(0, 5).map((post: any) => (
<li key={post.id} className="mb-2 p-4 border rounded hover:bg-gray-50">
{post.title}
</li>
))}
</ul>
</div>
);
}

7. 结语

这只是 Next.js 的冰山一角。它还有更多强大的功能,如:

  • API Routes:在 app/api 中构建后端接口。
  • Middleware:请求拦截与处理。
  • Image Optimization:使用 <Image /> 组件自动优化图片。

希望这篇指南能帮你快速开启 Next.js 开发之旅!