Next.js 安装
·
Next.js 安装与学习笔记
1. 环境准备
在开始之前,确保你的开发环境满足以下要求:
- Node.js: 版本 18.17 或更高(推荐 LTS 版本)
- npm: 通常随 Node.js 一起安装
- 包管理器: npm, yarn, pnpm 或 bun 均可
检查版本:
node -v
npm -v
2. 创建新项目
方法一:使用 create-next-app(官方推荐)
# 使用 npm
npx create-next-app@latest my-next-app
# 使用 yarn
yarn create next-app my-next-app
# 使用 pnpm
pnpm create next-app my-next-app
交互式配置选项:
- TypeScript: 推荐选择 Yes
- ESLint: 推荐选择 Yes
- Tailwind CSS: 根据需求选择
src/目录: 推荐选择 Yes(保持项目结构清晰)- App Router: 必须选择 Yes(Next.js 13+ 的新架构)
- 自定义导入别名: 可选
方法二:手动初始化
mkdir my-next-app
cd my-next-app
npm init -y
npm install next react react-dom
然后在 package.json 中添加脚本:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
}
}
3. 项目结构解析
my-next-app/
├── src/
│ ├── app/ # App Router 页面(Next.js 13+)
│ │ ├── layout.tsx # 根布局
│ │ ├── page.tsx # 首页
│ │ └── ...
│ ├── components/ # 可复用组件
│ └── lib/ # 工具函数
├── public/ # 静态资源
├── .env.local # 环境变量
├── next.config.js # Next.js 配置
├── package.json
└── tsconfig.json # TypeScript 配置
4. 核心概念速记
4.1 App Router 路由系统
- 文件即路由:
app/page.tsx→/,app/about/page.tsx→/about - 动态路由:
app/blog/[slug]/page.tsx→/blog/my-post - 嵌套路由:
app/dashboard/settings/page.tsx→/dashboard/settings - 布局系统:
layout.tsx在路由段中共享 UI
4.2 服务端组件 vs 客户端组件
- 服务端组件(默认): 在服务器渲染,不能直接使用
useState,useEffect - 客户端组件: 添加
'use client'指令,支持交互和状态管理
// 服务端组件(默认)
export default function Page() {
return <h1>Hello</h1>;
}
// 客户端组件
'use client';
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
4.3 数据获取
// 服务端组件中直接 await 获取数据
async function getData() {
const res = await fetch('https://api.example.com/data');
return res.json();
}
export default async function Page() {
const data = await getData();
return <div>{data.title}</div>;
}
5. 常用命令
# 开发模式(热更新)
npm run dev
# 生产构建
npm run build
# 启动生产服务器
npm start
# 代码检查
npm run lint
# 类型检查
npx tsc --noEmit
6. 配置要点
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: ['example.com'], // 允许的外部图片域名
},
// 环境变量前缀
env: {
API_URL: process.env.API_URL,
},
};
module.exports = nextConfig;
环境变量
.env.local: 本地开发(不提交到 Git).env.production: 生产环境- 变量名必须以
NEXT_PUBLIC_开头才能在客户端访问
7. 最佳实践
- 优先使用服务端组件: 减少客户端 JavaScript 体积
- 合理使用
'use client': 只在需要交互时添加 - 利用 Layout 共享状态: 避免重复渲染
- 图片优化: 使用
next/image自动优化 - SEO 优化: 使用
generateMetadata动态生成元数据 - 错误处理: 使用
error.tsx和not-found.tsx
8. 常见问题
- 端口被占用:
npm run dev -- -p 3001 - 清除缓存:
rm -rf .next node_modules后重新安装 - TypeScript 错误: 检查
tsconfig.json配置 - 图片加载失败: 在
next.config.js中添加域名白名单
9. 下一步学习
- Next.js 官方文档
- App Router 深入理解
- 数据获取策略(缓存、重新验证)
- 中间件(Middleware)
- API Routes 与 Server Actions
- 部署到 Vercel 或其他平台
提示: Next.js 更新频繁,建议定期查看官方发布说明,了解新特性和最佳实践的变化。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)