跳到內容

專案結構與組織

本頁概述 Next.js 中的資料夾和檔案慣例,以及組織專案的技巧。

資料夾和檔案慣例

頂層資料夾

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

Route segments to path segments
appApp Router
pagesPages Router
public要提供的靜態資源
src選用的應用程式原始碼資料夾

頂層檔案

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

Next.js
next.config.jsNext.js 的設定檔
package.json專案依賴套件和指令碼
instrumentation.tsOpenTelemetry 和檢測檔案
middleware.tsNext.js 請求中介軟體
.env環境變數
.env.local本機環境變數
.env.production生產環境變數
.env.development開發環境變數
.eslintrc.jsonESLint 的設定檔
.gitignore要忽略的 Git 檔案和資料夾
next-env.d.tsNext.js 的 TypeScript 宣告檔案
tsconfig.jsonTypeScript 的設定檔
jsconfig.jsonJavaScript 的設定檔

檔案慣例

_app.js .jsx .tsxCustom App
_document.js .jsx .tsxCustom 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動態路由區段
[...folder]/index.js .jsx .tsx捕捉所有路由區段
[[...folder]]/index.js .jsx .tsx選用的捕捉所有路由區段
檔案慣例
[file].js .jsx .tsx動態路由區段
[...file].js .jsx .tsx捕捉所有路由區段
[[...file]].js .jsx .tsx選用的捕捉所有路由區段