Nextjs|App Router

项目结构

按照官方文档提供的最佳实践项目,其目录结构如下

1
npx create-next-app@latest nextjs-dashboard --example "https://github.com/vercel/next-learn/tree/main/dashboard/starter-example" --use-pnpm
  • **/app**:包含应用程序的所有路由、组件和具体实现逻辑,这是项目核心代码
  • **/app/lib**:包含应用程序中使用的函数,例如可重用的实用程序函数和数据获取函数
  • **/app/ui**:包含应用程序的所有 UI 组件,例如卡片、表格和表单。为了节省时间,我们已为您预先设计了这些组件的样式
  • **/public**:包含应用程序的所有静态资产,例如图像
  • 配置文件:您还会注意到配置文件,例如位于根目录的next.config.ts文件。大多数此类文件都是在使用create-next-app命令后自动生成和预先配置的,无需在此次开发中修改它们

Mock数据

写真前端的时候需要数据,常见的数据占位方式有两种:

  • 以JS对象的方式写死在代码中
  • 使用Mock API等第三方服务

本次我们就使用JS对象的方式进行预定义,具体存放在/app/lib/placeholder-data.ts这个文件中,每一个对象对应数据库的一张表

TypeScript

/app/lib/definitions.ts文件手动定义将从数据库返回的数据的类型

1
2
3
4
5
6
7
8
9
export type Invoice = {
id: string;
customer_id: string;
amount: number;
date: string;
// In TypeScript, this is called a string union type.
// It means that the "status" property can only be one of the two strings: 'pending' or 'paid'.
status: 'pending' | 'paid';
};

这样就保证了不会意外地将错误的数据格式传递给组件或数据库,例如针对amount字段不会是String而是number进行传递

设置样式


Nextjs|App Router
http://example.com/2025/03/28/Nextjs-App-Router/
作者
Noctis64
发布于
2025年3月28日
许可协议