一套 真正 可用 的 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/*"]
}
}
}