Skip to main content

项目结构

本页概述了 Next.js 项目的文件和文件夹结构. 内容包括顶层文件和文件夹, 配置文件, app 目录和 pages 目录的路由约定.


Top-level folders (顶层文件夹)

文件夹名简述
appApp router
pagesPages Router
public静态资源
src可选的应用程序源文件夹

Top-level files (顶层文件)

文件名简述
next.config.jsNext.js 的配置文件
package.json项目依赖和脚本
instrument.tsOpenTelemetry and Instrumentation file
middleware.tsNext.js 请求中间件
.env环境变量
.env.local本地环境变量
.env.production生产环境变量
.env.development开发环境变量
.eslintrc.jsonESLint 的配置文件
.gitignoreGit 文件, 用以忽略文件和文件夹
next-env.d.tsNext.js 内的 Typescript 声明文件
tsconfig.jsonTypescript 的配置文件
jsconfig.jsonJavascript 的配置文件

app Routing Conventions (app Routing 协定)

Routing Files (路由文件)

文件名后缀名简述
layout.js | .jsx | .tsx布局
page.js | .jsx | .tsx页面
loading.js | .jsx | .tsx加载中 UI
not-found.js | .jsx | .tsx路由未找到时的 UI
error.js | .jsx | .tsx路由加载错误时的 UI
global-error.js | .jsx | .tsx全局下, 路由加载错误时的 UI
route.js | .jsxAPI 接口
template.js | .jsx | .tsx预渲染布局
default.js | .jsx | .tsx并行路由的 fallback page(应变页面)

Nested Routes (嵌套路由)

文件名简述
folder路由片段
folder/folder嵌套的路由片段

Dynamic Routes (动态路由)

文件名简述
[folder]动态路由片段
[...folder]捕获所有的路由段
[[...folder]]选择性的捕获所有的路由段

Routes Groups and Private Folders (路由组和私有文件夹)

文件名简述
(folder)不影响路由的路由组
_folder可选的文件夹, 所有的子文件/文件夹都被路由排除在外

Parallel and Intercepted Routes (平行路由和拦截路由)

文件名简述
@folder命名插槽
(.)folder拦截同一水平路由
(..)folder拦截上一级路由
(..)(..)folder拦截上两级路由
(...)folder由根路由开始拦截

Metadata File Convention (元文件协定)

App Icons (应用图标)

文件名后缀名简述
favicon.icoFavicon 文件
icon.ico | .jpg | .jpeg | .png | .svgApp Icon 文件
icon.js | .ts | .tsx生成的 App Icon 文件
apple-icon.jpg | .jpeg | .pngApple App
apple-icon.js | .ts | .tsx生成的 Apple App Icon 文件

Open Graph and Twitter Images

文件名后缀名简述
opengraph-image.jpg | .jpeg | .png | .gifOpen Graph image file
opengraph-image.js | .ts | .tsxGenerated Open Graph image
twitter-image.jpg | .jpeg | .png | .gifTwitter 图片文件
twitter-image.js | .ts | .tsx生成的 Twitter 图片

SEO

文件名后缀名简述
sitemap.xmlSitemap file
sitemap.js | .tsGenerated Sitemap
robots.txtRobots file
robots.js | .tsGenerated Robots file

pages Routing Convention (pages Router 协定)

Special Files (特殊文件)

文件名后缀名简述
_app.js | .ts | .tsx自定义的 App 文件
_document.js | .ts | .tsx自定义的 Document 文件
_error.js | .ts | .tsx自定义的, 错误出现时页面
404.js | .ts | .tsx404 错误出现时的页面
500.js | .ts | .tsx500 错误出现时的页面

Routes (路由)

Folder convention (文件夹方式)

文件/文件夹名后缀名简述
index.js | .ts | .tsx主页
folder/index.js | .ts | .tsx嵌套页面

File convention(文件方式)

文件/文件夹名后缀名简述
index.js | .ts | .tsx主页
file.js | .ts | .tsx嵌套页面

Dynamic Routes (动态路由)

Folder convention (文件夹方式)

文件/文件夹后缀名简述
[folder]/index.js | .ts | .tsx动态路由片段
[...folder]/index.js | .ts | .tsx捕获所有的路由片段
[[...folder]]/index.js | .ts | .tsx可选的, 捕获所有的路由片段

File convention (文件方式)

文件/文件夹后缀名简述
[file].js | .ts | .tsx动态路由片段
[...file].js | .ts | .tsx捕获所有的路由片段
[[...file]].js | .ts | .tsx可选的, 捕获所有的路由片段