專案結構與組織

本頁面提供 Next.js 中所有資料夾與檔案慣例的概述,以及組織專案的建議。

資料夾與檔案慣例

頂層資料夾

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

路由區段對應路徑區段
app應用路由 (App Router)
pages頁面路由 (Pages 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 設定檔
.gitignoreGit 忽略檔案與資料夾
next-env.d.tsNext.js 的 TypeScript 宣告檔案
tsconfig.jsonTypeScript 設定檔
jsconfig.jsonJavaScript 設定檔

檔案慣例

_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動態路由區段
[...folder]/index.js .jsx .tsx萬用路由區段
[[...folder]]/index.js .jsx .tsx可選的萬用路由區段
檔案慣例
[file].js .jsx .tsx動態路由區段
[...file].js .jsx .tsx萬用路由區段
[[...file]].js .jsx .tsx可選的萬用路由區段