Next.js 15 + TypeScript 从零教程
Next.js 15 是基于 React 的最新 Web 框架,提供了更强大的服务端渲染(SSR)、静态生成(SSG)、App Router(全新的路由系统)等功能。结合 TypeScript 开发可以提高代码的可维护性和安全性。本教程将从零开始,带你掌握 Next.js 15 + TypeScript 的核心概念和实践。
1. 环境准备
1.1 安装 Node.js
Next.js 15 需要 Node.js 16.8 或更高版本,推荐安装最新的 LTS 版本。
检查 Node.js 是否安装
node -v
npm -v
如果未安装,可前往 Node.js 官网 下载并安装。
1.2 创建 Next.js 15 + TypeScript 项目
运行以下命令创建项目:
npx create-next-app@latest my-next-ts-app --typescript
# 或者
yarn create next-app my-next-ts-app --typescript
# 或者
pnpm create next-app my-next-ts-app --typescript
进入项目目录:
cd my-next-ts-app
启动开发服务器
npm run dev
2. Next.js 目录结构
my-next-ts-app/
│── app/ # 主要的页面和布局 (App Router)
│ ├── layout.tsx # 全局布局组件
│ ├── page.tsx # 主页
│ ├── about/ # /about 页面
│ │ ├── page.tsx # /about/index
│── public/ # 静态资源(图片、字体等)
│── components/ # 复用组件
│── styles/ # 样式文件(CSS、Sass)
│── next.config.js # Next.js 配置文件
│── tsconfig.json # TypeScript 配置文件
│── package.json # 依赖和脚本
3. 使用 App Router (App 目录)
Next.js 15 默认使用 App Router(基于 React Server Components)。
所有页面都存放在 /app
目录下,page.tsx
代表一个路由。
3.1 创建基本页面
修改 app/page.tsx
作为主页:
export default function Home() {
return <h1 className="text-3xl font-bold">Hello Next.js 15 + TypeScript!</h1>;
}
创建 app/about/page.tsx
:
export default function About() {
return <h1>关于我们</h1>;
}
访问 http://localhost:3000/about 看到 /about
页面。
4. 组件化开发
在 components/
目录创建 Button.tsx
:
type ButtonProps = {
text: string;
};
export default function Button({ text }: ButtonProps) {
return <button className="px-4 py-2 bg-blue-500 text-white rounded">{text}</button>;
}
在 app/page.tsx
使用该组件:
import Button from "@/components/Button";
export default function Home() {
return (
<div>
<h1 className="text-3xl font-bold">Hello Next.js 15 + TypeScript!</h1>
<Button text="点击我" />
</div>
);
}
5. 路由
5.1 动态路由
创建 app/post/[id]/page.tsx
:
type PostProps = {
params: { id: string };
};
export default function Post({ params }: PostProps) {
return <h1>文章 ID: {params.id}</h1>;
}
访问 /post/123
,页面显示 文章 ID: 123
。
6. 数据获取
Next.js 15 提供了更现代化的数据获取方式 fetch()
内置支持 SSR、SSG。
6.1 服务器端渲染 (SSR)
在 app/page.tsx
获取数据:
async function getData() {
const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
return res.json();
}
export default async function Home() {
const data = await getData();
return <h1>{data.title}</h1>;
}
特性:
- 该函数在 服务器端执行,不会在客户端暴露 API 请求。
6.2 静态生成 (SSG)
创建 app/posts/page.tsx
:
async function getPosts() {
const res = await fetch("https://jsonplaceholder.typicode.com/posts", { cache: "force-cache" });
return res.json();
}
export default async function Posts() {
const posts = await getPosts();
return (
<div>
<h1>文章列表</h1>
<ul>
{posts.map((post: { id: number; title: string }) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
特性:
cache: "force-cache"
使页面在构建时生成,适用于不频繁更新的数据。
7. API 路由
在 app/api/hello/route.ts
创建 API:
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "Hello API!" });
}
访问 http://localhost:3000/api/hello 返回:
json
{"message": "Hello API!"}
8. 样式与 Tailwind CSS
8.1 安装 Tailwind
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
配置 tailwind.config.js
:
module.exports = {
content: ["./app/**/*.{ts,tsx}", "./components/**/*.{ts,tsx}"],
theme: { extend: {} },
plugins: [],
};
在 styles/globals.css
引入:
@tailwind base;
@tailwind components;
@tailwind utilities;
使用 Tailwind:
export default function Home() {
return <h1 className="text-3xl font-bold text-blue-500">Hello, Tailwind!</h1>;
}
9. 部署 Next.js 15
9.1 生成静态文件
npm run build
npm run start
9.2 部署到 Vercel
安装 Vercel CLI:
npm install -g vercel
部署:
vercel
按照提示操作,即可完成部署。
总结
本教程介绍了:
✅ Next.js 15 + TypeScript 安装与目录结构
✅ 使用 App Router 开发页面
✅ 动态路由 和 数据获取(SSR、SSG)
✅ API 路由 和 组件化开发
✅ Tailwind CSS 样式
✅ 部署到 Vercel
现在,你可以用 Next.js 15 + TypeScript 构建高效、现代化的 Web 应用!🚀
Next.js 之所以非常快,主要是因为它采用了一系列优化技术,使得页面加载更快、交互更流畅,同时提升 SEO 和性能。下面是 Next.js 速度快的几个核心原因:
1. 预渲染(Pre-rendering)
Next.js 默认在服务器端或构建时 预渲染页面,而不是等到浏览器加载 JavaScript 后再渲染。预渲染方式有两种:
- 静态生成(SSG,Static Site Generation):在构建时生成 HTML,提高加载速度,并可配合增量静态再生(ISR)。
- 服务器端渲染(SSR,Server Side Rendering):请求时动态生成页面,适用于实时数据。
对比:传统 React 需要在客户端渲染,而 Next.js 直接返回 HTML,让用户能更快看到页面内容。
2. 自动代码拆分(Automatic Code Splitting)
Next.js 只加载 当前页面所需的 JavaScript 代码,而不会加载整个应用的 JavaScript:
- 页面级别的代码拆分(仅加载当前访问的页面)
- 组件级别的代码拆分(动态导入
import()
) next/dynamic
组件按需加载,减少初始加载体积
💡 示例:
import dynamic from "next/dynamic";
const HeavyComponent = dynamic(() => import("../components/HeavyComponent"), {
ssr: false,
});
这样,HeavyComponent
组件不会在服务器端渲染,也不会在首页加载时被加载,只有在需要时才会加载,提高页面加载速度。
3. 增量静态再生(ISR,Incremental Static Regeneration)
Next.js 允许你 部分更新静态页面,而不需要重新构建整个网站。例如:
export async function getStaticProps() {
const res = await fetch("https://api.example.com/posts");
const posts = await res.json();
return {
props: { posts },
revalidate: 10, // 每 10 秒重新生成页面
};
}
这意味着即使页面已预渲染,也可以按需更新数据,而 不会影响现有的访问用户,提升性能。
4. 服务器组件(React Server Components,RSC)
Next.js 15 使用 React 服务器组件(Server Components),允许服务器端处理数据,然后将轻量的 HTML 发送到客户端:
- 服务器渲染不发送 JavaScript 代码,减小页面体积
- 避免在客户端运行昂贵的计算任务
- 组件级别优化,减少客户端渲染的负担
💡 示例:
export default async function ServerComponent() {
const data = await fetch("https://api.example.com/data").then(res => res.json());
return <h1>{data.title}</h1>;
}
特点:
- 这个组件不会在客户端执行
fetch()
,而是在服务器上完成数据获取并返回 HTML。 - 减少 JavaScript 体积,提高加载速度。
5. 内置 CDN 和 Edge Functions
Next.js 自动将静态资源(CSS、JS、图片等)存储在 CDN(内容分发网络) 上,减少服务器压力,提高全球用户访问速度:
- CDN 分发加速(自动缓存静态资源)
- Edge Functions(边缘计算) 让 API 处理更快,接近用户所在地
💡 示例(Vercel Edge Functions):
export const config = {
runtime: "edge",
};
export default async function handler(req) {
return new Response("Hello, Edge!", { status: 200 });
}
优势:
- 运行在全球边缘服务器,而不是集中在单个数据中心
- API 请求速度更快,减少网络延迟
6. 图像优化(next/image)
Next.js 内置了 next/image
组件,提供 懒加载、自动压缩、格式转换(WebP)、CDN 加速:
import Image from "next/image";
import myImage from "../public/my-image.jpg";
export default function Page() {
return <Image src={myImage} alt="My Image" width={500} height={300} />;
}
优化点:
- 仅加载视口内的图片(Lazy Load)
- 自动生成适应不同设备的图片(Responsive)
- 使用现代格式(WebP、AVIF)
📌 比
<img>
更高效,减少图片加载时间,提升页面速度。
7. API 路由优化
Next.js 允许在 app/api/
目录创建 API 路由,并自动优化:
- 按需加载 API 代码
- 无服务器(Serverless)架构,仅在请求时执行
- 内置缓存,提高响应速度
💡 示例:
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "Hello, API!" });
}
这个 API 只在访问时运行,不会一直占用服务器资源,降低性能损耗。
8. 高效的 React 渲染
Next.js 结合 React 18 并发模式 和 Suspense,减少不必要的重新渲染:
- 自动批量更新(减少 Re-render 次数)
- React Server Components(服务器端渲染更轻量)
- Concurrent Mode 并发更新 UI
- Streaming(流式渲染,页面更快可交互)
9. 多层缓存优化
Next.js 自动管理缓存,避免重复计算:
- 静态文件缓存(CSS、JS、HTML)
- API 请求缓存(
fetch()
自动缓存) - 图像缓存(
next/image
生成优化版本) - Edge Caching(边缘缓存) 让全球用户访问更快
10. 按需加载(Lazy Loading)
Next.js 允许组件、模块按需加载,减少初始 JavaScript 体积:
import dynamic from "next/dynamic";
const HeavyComponent = dynamic(() => import("../components/HeavyComponent"), {
loading: () => <p>Loading...</p>,
});
- 只有当用户需要时才加载
HeavyComponent
- 避免影响首屏渲染速度
总结:为什么 Next.js 这么快?
✅ 服务器端渲染(SSR):直接返回 HTML,减少客户端计算量
✅ 静态生成(SSG + ISR):缓存页面,按需更新,减少数据库请求
✅ 自动代码拆分(Code Splitting):只加载当前页面所需代码
✅ React Server Components(RSC):服务器端渲染更轻量
✅ Edge Functions(边缘计算):减少 API 延迟,提升速度
✅ CDN + 缓存优化:全局加速,提高数据访问效率
✅ next/image 自动优化:减少图片加载时间
✅ Lazy Loading(按需加载):减少初始 JavaScript 体积
✅ 内置多层缓存:自动管理静态文件、API 请求缓存
🚀 总结一句话:Next.js 通过服务器端渲染、智能缓存、代码拆分、按需加载等方式,使页面加载更快、交互更流畅,是目前最快的 React 框架之一。