一套真正可用的 Next.js(App Router)项目结构
本文由原文机器翻译。
正在加载文章...
正在加载文章...
本文由原文机器翻译。
结构良好的文件夹布局会为你的开发工作流带来显著收益。下面是一套简洁且可扩展的架构,适用于 Next.js 13+ App Router 项目,它能让你的代码库随着增长保持可维护。
project-root/
├─ app/ # App Router entry (Next.js 13+)
│ ├─ layout.tsx # Global layout (nav, fonts, theme)
│ ├─ page.tsx # Home page ("/")
│ ├─ api/ # Route Handlers (serverless APIs)
│ │ └─ v1/
│ │ └─ auth/
│ │ └─ route.ts # e.g. POST /api/v1/auth
│ ├─ dashboard/
│ │ ├─ layout.tsx # Dashboard-specific layout
│ │ ├─ page.tsx # "/dashboard"
│ │ └─ reports/
│ │ └─ page.tsx # "/dashboard/reports"
│ └─ error.tsx # Global error boundary
│
├─ components/ # Reusable UI components
│ ├─ Header/ Header.tsx
│ ├─ Footer/ Footer.tsx
│ └─ Button/ Button.tsx
│
├─ hooks/ # Custom React hooks
│ ├─ useAuth.ts
│ └─ useFetch.ts
│
├─ services/ # API/service layer (no UI here)
│ ├─ user/ userService.ts
│ └─ product/ productService.ts
│
├─ styles/ # Styling
│ ├─ globals.css # Imported in app/layout.tsx
│ ├─ variables.css # CSS vars / themes
│ └─ components/
│ ├─ Button.module.css
│ └─ Header.module.css
│
├─ types/ # Shared TypeScript types
│ └─ exampleDataType.ts
│
├─ public/ # Static assets (images, fonts, favicon)
│
├─ tests/ # Tests (unit/integration/e2e)
│ ├─ unit/
│ ├─ integration/
│ └─ e2e/
│
├─ .env.local # Local env vars (gitignored)
├─ next.config.js
├─ tsconfig.json
└─ package.json专业提示:优先采用 就近放置 (在合适的时候)
// app/api/v1/auth/route.ts
import { NextResponse } from 'next/server';
export async function POST(req: Request) {
const body = await req.json();
// auth logic here…
return NextResponse.json({ ok: true });
}服务端组件与客户端组件
'use client';
import { useEffect, useState } from 'react';
export function useFetch<T>(url: string) {
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<unknown>(null);
useEffect(() => {
let alive = true;
fetch(url)
.then(r => r.json())
.then(d => alive && setData(d))
.catch(e => alive && setError(e));
return () => { alive = false; };
}, [url]);
return { data, error };
}// services/user/userService.ts
export async function getUserProfile(token: string) {
const res = await fetch(`${process.env.NEXT_PUBLIC_API}/v1/user`, {
headers: { Authorization: `Bearer ${token}` },
next: { revalidate: 60 }, // ISR-style revalidation
});
if (!res.ok) throw new Error('Failed to load profile');
return res.json() as Promise<User>;
}命名约定:使用 *.test.ts(x),并且如果你的团队偏好就近放置,可以考虑将测试放在它们所验证的代码附近。
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@components/*": ["components/*"],
"@services/*": ["services/*"],
"@hooks/*": ["hooks/*"]
}
}
}