找回密码
 立即注册
首页 业界区 业界 Next.js 14 基础入门:从项目搭建到核心概念 ...

Next.js 14 基础入门:从项目搭建到核心概念

澹台吉星 前天 18:49
Next.js 14 带来了许多激动人心的新特性,包括局部渲染、Server Actions 增强等。作为一名前端开发者,我最近在项目中升级到了 Next.js 14,今天就来分享一下从项目搭建到实际应用的完整过程。
项目初始化

首先,让我们创建一个全新的 Next.js 14 项目:
  1. # 使用 create-next-app 创建项目
  2. npx create-next-app@latest my-next-app
复制代码
在初始化过程中,你会看到以下选项:
  1. ✔ Would you like to use TypeScript? Yes
  2. ✔ Would you like to use ESLint? Yes
  3. ✔ Would you like to use Tailwind CSS? Yes
  4. ✔ Would you like to use `src/` directory? Yes
  5. ✔ Would you like to use App Router? Yes
  6. ✔ Would you like to customize the default import alias? No
复制代码
目录结构解析

创建完成后,我们来看看项目的核心目录结构:
  1. my-next-app/
  2. ├── src/
  3. │   ├── app/
  4. │   │   ├── layout.tsx      # 根布局文件
  5. │   │   ├── page.tsx        # 首页组件
  6. │   │   ├── error.tsx       # 错误处理组件
  7. │        ├── loading.tsx     # 加载状态组件
  8. │   │   └── not-found.tsx   # 404页面组件
  9. │   ├── components/         # 组件目录
  10. │   └── lib/               # 工具函数目录
  11. ├── public/                # 静态资源目录
  12. ├── next.config.js        # Next.js 配置文件
  13. └── package.json          # 项目依赖配置
复制代码
App Router 基础

Next.js 14 推荐使用 App Router,它基于 React Server Components,提供了更好的性能和开发体验。
1. 基础路由
  1. // src/app/page.tsx - 首页
  2. export default function Home() {
  3.   return (
  4.     <main className="flex min-h-screen flex-col items-center justify-between p-24">
  5.       <h1>Welcome to Next.js 14</h1>
  6.     </main>
  7.   );
  8. }
  9. // src/app/about/page.tsx - 关于页面
  10. export default function About() {
  11.   return (
  12.    
  13.       <h1>About Us</h1>
  14.    
  15.   );
  16. }
复制代码
2. 布局组件
  1. // src/app/layout.tsx
  2. export default function RootLayout({
  3.   children,
  4. }: {
  5.   children: React.ReactNode;
  6. }) {
  7.   return (
  8.     <html lang="en">
  9.       <body>
  10.         <header>
  11.           <nav>{/* 导航栏组件 */}</nav>
  12.         </header>
  13.         <main>{children}</main>
  14.         <footer>{/* 页脚组件 */}</footer>
  15.       </body>
  16.     </html>
  17.   );
  18. }
  19. // src/app/blog/layout.tsx - 博客专属布局
  20. export default function BlogLayout({
  21.   children,
  22. }: {
  23.   children: React.ReactNode;
  24. }) {
  25.   return (
  26.    
  27.       
  28.         {/* 博客侧边栏 */}
  29.       </aside>
  30.       
  31.         {children}
  32.       
  33.    
  34.   );
  35. }
复制代码
数据获取

Next.js 14 提供了多种数据获取方式,默认都是基于 Server Components:
1. 服务端获取数据
  1. // src/app/posts/page.tsx
  2. async function getPosts() {
  3.   const res = await fetch('https://api.example.com/posts', {
  4.     next: {
  5.       revalidate: 3600 // 1小时重新验证一次
  6.     }
  7.   });
  8.   
  9.   if (!res.ok) {
  10.     throw new Error('Failed to fetch posts');
  11.   }
  12.   
  13.   return res.json();
  14. }
  15. export default async function Posts() {
  16.   const posts = await getPosts();
  17.   
  18.   return (
  19.    
  20.       {posts.map(post => (
  21.         <PostCard key={post.id} post={post} />
  22.       ))}
  23.    
  24.   );
  25. }
复制代码
2. 动态路由数据获取
  1. // src/app/posts/[id]/page.tsx
  2. async function getPost(id: string) {
  3.   const res = await fetch(`https://api.example.com/posts/${id}`, {
  4.     cache: 'no-store' // 禁用缓存,始终获取最新数据
  5.   });
  6.   
  7.   if (!res.ok) {
  8.     throw new Error('Failed to fetch post');
  9.   }
  10.   
  11.   return res.json();
  12. }
  13. export default async function Post({
  14.   params: { id }
  15. }: {
  16.   params: { id: string }
  17. }) {
  18.   const post = await getPost(id);
  19.   
  20.   return (
  21.    
  22.       <h1>{post.title}</h1>
  23.       {post.content}
  24.     </article>
  25.   );
  26. }
复制代码
Server Actions

Next.js 14 增强了 Server Actions,让表单处理变得更简单:
  1. // src/app/posts/new/page.tsx
  2. export default function NewPost() {
  3.   async function createPost(formData: FormData) {
  4.     'use server';
  5.    
  6.     const title = formData.get('title');
  7.     const content = formData.get('content');
  8.    
  9.     // 服务端验证
  10.     if (!title || !content) {
  11.       throw new Error('Title and content are required');
  12.     }
  13.    
  14.     // 直接在服务端处理数据
  15.     await db.post.create({
  16.       data: {
  17.         title: title as string,
  18.         content: content as string,
  19.       },
  20.     });
  21.    
  22.     // 重定向到文章列表
  23.     redirect('/posts');
  24.   }
  25.   
  26.   return (
  27.     <form action={createPost}>
  28.       <input type="text" name="title" placeholder="文章标题" />
  29.       <textarea name="content" placeholder="文章内容" />
  30.       <button type="submit">发布文章</button>
  31.     </form>
  32.   );
  33. }
复制代码
客户端组件

虽然 Server Components 是默认的,但有时我们需要客户端交互:
  1. // src/components/Counter.tsx
  2. 'use client';
  3. import { useState } from 'react';
  4. export default function Counter() {
  5.   const [count, setCount] = useState(0);
  6.   
  7.   return (
  8.    
  9.       <p>Count: {count}</p>
  10.       <button onClick={() => setCount(count + 1)}>
  11.         Increment
  12.       </button>
  13.    
  14.   );
  15. }
复制代码
元数据配置

Next.js 14 提供了强大的元数据 API:
  1. // src/app/layout.tsx
  2. import { Metadata } from 'next';
  3. export const metadata: Metadata = {
  4.   title: {
  5.     template: '%s | My Next.js App',
  6.     default: 'My Next.js App',
  7.   },
  8.   description: 'Built with Next.js 14',
  9.   openGraph: {
  10.     title: 'My Next.js App',
  11.     description: 'Built with Next.js 14',
  12.     images: ['/og-image.jpg'],
  13.   },
  14. };
  15. // src/app/blog/[slug]/page.tsx
  16. export async function generateMetadata({
  17.   params
  18. }: {
  19.   params: { slug: string }
  20. }): Promise<Metadata> {
  21.   const post = await getPost(params.slug);
  22.   
  23.   return {
  24.     title: post.title,
  25.     description: post.excerpt,
  26.     openGraph: {
  27.       title: post.title,
  28.       description: post.excerpt,
  29.       images: [post.coverImage],
  30.     },
  31.   };
  32. }
复制代码
静态资源处理

Next.js 14 优化了图片和字体的处理:
  1. // src/components/ProfileImage.tsx
  2. import Image from 'next/image';
  3. export default function ProfileImage() {
  4.   return (
  5.     <Image
  6.       src="/profile.jpg"
  7.       alt="Profile"
  8.       width={200}
  9.       height={200}
  10.       placeholder="blur"
  11.       blurDataURL="data:image/jpeg;base64,..."
  12.       priority
  13.     />
  14.   );
  15. }
  16. // src/app/layout.tsx
  17. import { Inter } from 'next/font/google';
  18. const inter = Inter({
  19.   subsets: ['latin'],
  20.   display: 'swap',
  21. });
  22. export default function RootLayout({
  23.   children,
  24. }: {
  25.   children: React.ReactNode;
  26. }) {
  27.   return (
  28.     <html lang="en" className={inter.className}>
  29.       <body>{children}</body>
  30.     </html>
  31.   );
  32. }
复制代码
环境配置

Next.js 14 支持多环境配置:
  1. # .env.local
  2. DATABASE_URL="postgresql://..."
  3. API_KEY="your-api-key"
  4. # .env.production
  5. NEXT_PUBLIC_API_URL="https://api.production.com"
  6. # .env.development
  7. NEXT_PUBLIC_API_URL="http://localhost:3000"
复制代码
使用环境变量:
  1. // src/lib/db.ts
  2. const dbUrl = process.env.DATABASE_URL;
  3. const apiKey = process.env.API_KEY;
  4. // 客户端也可以使用 NEXT_PUBLIC_ 前缀的环境变量
  5. console.log(process.env.NEXT_PUBLIC_API_URL);
复制代码
错误处理

Next.js 14 提供了完善的错误处理机制:
  1. // src/app/error.tsx
  2. 'use client';
  3. export default function Error({
  4.   error,
  5.   reset,
  6. }: {
  7.   error: Error;
  8.   reset: () => void;
  9. }) {
  10.   return (
  11.    
  12.       <h2>Something went wrong!</h2>
  13.       <p>{error.message}</p>
  14.       <button onClick={() => reset()}>Try again</button>
  15.    
  16.   );
  17. }
  18. // src/app/not-found.tsx
  19. export default function NotFound() {
  20.   return (
  21.    
  22.       <h2>404 - Page Not Found</h2>
  23.       <p>Could not find requested resource</p>
  24.    
  25.   );
  26. }
复制代码
开发调试

Next.js 14 改进了开发体验:
  1. // 使用 React Developer Tools
  2. import { useDebugValue } from 'react';
  3. function useCustomHook() {
  4.   const value = // ... 一些计算
  5.   
  6.   // 在 React DevTools 中显示自定义值
  7.   useDebugValue(value, value => `Custom: ${value}`);
  8.   
  9.   return value;
  10. }
  11. // 使用 next.config.js 配置开发环境
  12. /** @type {import('next').NextConfig} */
  13. const nextConfig = {
  14.   reactStrictMode: true,
  15.   // 启用详细的构建输出
  16.   logging: {
  17.     fetches: {
  18.       fullUrl: true,
  19.     },
  20.   },
  21.   // 配置重写规则
  22.   rewrites: async () => {
  23.     return [
  24.       {
  25.         source: '/api/:path*',
  26.         destination: 'http://localhost:3001/api/:path*',
  27.       },
  28.     ];
  29.   },
  30. };
  31. module.exports = nextConfig;
复制代码
写在最后

Next.js 14 带来了许多激动人心的新特性,特别是在性能优化和开发体验方面有了显著提升。这篇文章介绍的只是基础功能,在实际项目中,你还可以:

  • 使用 Middleware 进行路由控制
  • 配置国际化路由
  • 实现增量静态再生成(ISR)
  • 使用 Edge Runtime 优化性能
  • 集成各种第三方服务
在接下来的系列文章中,我们会深入探讨这些进阶主题。如果你对某个特定主题特别感兴趣,欢迎在评论区告诉我!

如果觉得这篇文章对你有帮助,别忘了点个赞
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册