项目组织和文件并置
除了路由文件夹和文件约定之外,Next.js 对如何组织和并置你的项目文件**没有强加任何意见**。
此页面分享了你可以用来组织项目的默认行为和功能。
默认情况下安全地并置
在 app
目录中,嵌套文件夹层次结构 定义了路由结构。
每个文件夹表示一个路由段,该路由段映射到 URL 路径中的相应段。
但是,即使路由结构是通过文件夹定义的,在将 page.js
或 route.js
文件添加到路由段之前,**路由也无法公开访问**。


而且,即使路由已公开访问,也只有 page.js
或 route.js
返回的**内容**才会发送到客户端。


这意味着**项目文件**可以**安全地并置**在 app
目录中的路由段内,而不会意外地成为可路由的。


需要知道:
- 这与
pages
目录不同,在pages
目录中,任何文件都被视为路由。- 虽然你**可以**在
app
中并置你的项目文件,但你**不必**这样做。如果你愿意,你可以将它们保留在app
目录之外。
项目组织功能
Next.js 提供了一些功能来帮助你组织项目。
私有文件夹
私有文件夹可以通过在文件夹名前缀下划线来创建:_folderName
这表示该文件夹是私有的实现细节,路由系统不应考虑它,从而使**该文件夹及其所有子文件夹**退出路由。


由于 app
目录中的文件可以默认情况下安全地并置,因此私有文件夹不需要用于并置。但是,它们对于以下方面很有用
- 将 UI 逻辑与路由逻辑分离。
- 在整个项目和 Next.js 生态系统中一致地组织内部文件。
- 在代码编辑器中对文件进行排序和分组。
- 避免与未来的 Next.js 文件约定发生潜在的命名冲突。
需要知道:
- 虽然这不是框架约定,但你也可以考虑使用相同的下划线模式将私有文件夹外的文件标记为“私有”。
- 你可以创建以下划线开头的 URL 段,方法是在文件夹名前缀
%5F
(下划线的 URL 编码形式):%5FfolderName
。- 如果你不使用私有文件夹,了解 Next.js 的特殊文件约定 对于防止意外的命名冲突将会有所帮助。
路由组
路由组可以通过将文件夹括在括号中来创建:(folderName)
这表示该文件夹用于组织目的,不应包含在路由的 URL 路径中。


路由组对于以下方面很有用
- 将路由组织成组,例如按站点部分、意图或团队。
- 在同一路由段级别启用嵌套布局
src
目录
Next.js 支持将应用程序代码(包括 app
)存储在可选的 src
目录 中。这将应用程序代码与项目配置文件分开,这些文件主要位于项目的根目录中。


模块路径别名
Next.js 支持 模块路径别名,这使得在深度嵌套的项目文件中更容易读取和维护导入。
// before
import { Button } from '../../../components/button'
// after
import { Button } from '@/components/button'
项目组织策略
在组织 Next.js 项目中的文件和文件夹时,没有绝对的“正确”或“错误”的方法。
以下部分列出了常见策略的非常高级别的概述。最简单的要点是选择适合您和您的团队的策略,并在整个项目中保持一致。
请注意:在我们下面的示例中,我们使用
components
和lib
文件夹作为广义的占位符,它们的命名对框架没有特殊意义,您的项目可能使用其他文件夹,例如ui
、utils
、hooks
、styles
等。
将项目文件存储在 app
之外
此策略将所有应用程序代码存储在**项目根目录**中的共享文件夹中,并使 app
目录仅用于路由目的。


将项目文件存储在 app
内部的顶级文件夹中
此策略将所有应用程序代码存储在**app
目录的根目录**中的共享文件夹中。


按功能或路由拆分项目文件
此策略将全局共享的应用程序代码存储在根 app
目录中,并将更具体的应用程序代码**拆分**到使用它们的路由段中。


后续步骤
这有帮助吗?