Next.js 專案結構

本頁提供 Next.js 應用程式的專案結構概覽,涵蓋頂層檔案與資料夾、設定檔,以及 apppages 目錄中的路由慣例。

點擊檔案與資料夾名稱以深入了解各項慣例。

頂層資料夾

頂層資料夾用於組織應用程式的程式碼與靜態資源。

路由區段對應路徑區段
appApp 路由器 (App Router)
pages頁面路由器 (Pages Router)
public需提供的靜態資源
src可選的應用程式原始碼資料夾

頂層檔案

頂層檔案用於設定應用程式、管理依賴項、執行中介軟體、整合監控工具,以及定義環境變數。

Next.js
next.config.jsNext.js 設定檔
package.json專案依賴項與腳本
instrumentation.tsOpenTelemetry 與 Instrumentation 檔案
middleware.tsNext.js 請求中介軟體
.env環境變數
.env.local本地環境變數
.env.production生產環境變數
.env.development開發環境變數
.eslintrc.jsonESLint 設定檔
.gitignoreGit 忽略的檔案與資料夾
next-env.d.tsNext.js 的 TypeScript 宣告檔
tsconfig.jsonTypeScript 設定檔
jsconfig.jsonJavaScript 設定檔

app 路由慣例

以下檔案慣例用於在 app 路由器 中定義路由與處理元資料。

路由檔案

layout.js .jsx .tsx版面配置 (Layout)
page.js .jsx .tsx頁面 (Page)
loading.js .jsx .tsx載入 UI (Loading UI)
not-found.js .jsx .tsx找不到頁面 UI (Not found UI)
error.js .jsx .tsx錯誤 UI (Error UI)
global-error.js .jsx .tsx全域錯誤 UI (Global error UI)
route.js .tsAPI 端點 (API endpoint)
template.js .jsx .tsx重新渲染的版面配置
default.js .jsx .tsx平行路由後備頁面

巢狀路由

folder路由區段 (Route segment)
folder/folder巢狀路由區段 (Nested route segment)

動態路由

[folder]動態路由區段 (Dynamic route segment)
[...folder]全捕捉路由區段 (Catch-all route segment)
[[...folder]]可選全捕捉路由區段 (Optional catch-all route segment)

路由群組與私有資料夾

(folder)不影響路由的路由群組 (Group routes)
_folder將資料夾及其子區段排除在路由外 (Private folders)

平行與攔截路由

@folder命名插槽 (Named slot)
(.)folder攔截同層級路由
(..)folder攔截上一層級路由
(..)(..)folder攔截上兩層級路由
(...)folder從根層級攔截路由

元資料檔案慣例

應用圖示

favicon.ico網站圖示檔案 (Favicon)
icon.ico .jpg .jpeg .png .svg應用圖示檔案
icon.js .ts .tsx生成的應用圖示
apple-icon.jpg .jpeg, .pngApple 應用圖示檔案
apple-icon.js .ts .tsx生成的 Apple 應用圖示

Open Graph 與 Twitter 圖片

opengraph-image.jpg .jpeg .png .gifOpen Graph 圖片檔案
opengraph-image.js .ts .tsx生成的 Open Graph 圖片
twitter-image.jpg .jpeg .png .gifTwitter 圖片檔案
twitter-image.js .ts .tsx生成的 Twitter 圖片

SEO

sitemap.xml網站地圖檔案 (Sitemap)
sitemap.js .ts生成的網站地圖
robots.txtRobots 檔案
robots.js .ts生成的 Robots 檔案

pages 路由慣例

以下檔案慣例用於在 pages 路由器 中定義路由。

特殊檔案

_app.js .jsx .tsx自訂 App
_document.js .jsx .tsx自訂 Document
_error.js .jsx .tsx自訂錯誤頁面
404.js .jsx .tsx404 錯誤頁面
500.js .jsx .tsx500 錯誤頁面

路由

資料夾慣例
index.js .jsx .tsx首頁
folder/index.js .jsx .tsx巢狀頁面
檔案慣例
index.js .jsx .tsx首頁
file.js .jsx .tsx巢狀頁面

動態路由

資料夾慣例
[folder]/index.js .jsx .tsx動態路由區段 (Dynamic route segment)
[...folder]/index.js .jsx .tsx全捕捉路由區段 (Catch-all route segment)
[[...folder]]/index.js .jsx .tsx可選全捕捉路由區段 (Optional catch-all route segment)
檔案慣例
[file].js .jsx .tsx動態路由區段 (Dynamic route segment)
[...file].js .jsx .tsx全捕捉路由區段 (Catch-all route segment)
[[...file]].js .jsx .tsx可選全捕捉路由區段 (Optional catch-all route segment)

On this page