🐡
react, nextのディレクトリ構成
最近どんなディレクトリ構成がいいのか悩んでいるので吐き出す
改善点あればご意見いただけるとありがたいです。
Next.js & React プロジェクト構成ガイド
1. プロジェクト作成
npx create-next-app@latest my-app --use-npm --typescript --src-dir
cd my-app
2. ディレクトリ構成の具体例
以下のディレクトリ構成を画像およびコードブロックで表示します。
my-app/
├ .next/
├ node_modules/
├ public/
│ └ …
├ src/
│ ├ app/
│ │ ├ layout.tsx # アプリ共通レイアウト (ヘッダー・フッター)
│ │ ├ page.tsx # トップページ
│ │ ├ dashboard/
│ │ │ ├ page.tsx # Dashboard ページ
│ │ │ ├ components/ # ページ固有コンポーネント
│ │ │ │ └ DashboardWidget.tsx
│ │ │ └ hooks/ # ページ固有フック
│ │ │ └ useDashboardData.ts
│ ├ common/
│ │ ├ components/ # 全体共通UIコンポーネント
│ │ │ ├ Button.tsx
│ │ │ └ Modal.tsx
│ │ └ utils/ # 全体共通ユーティリティ関数
│ │ ├ dateUtils.ts
│ │ └ stringUtils.ts
│ ├ feature/ # ドメイン機能ごと
│ │ ├ account/
│ │ │ ├ components/
│ │ │ │ ├ AccountList.tsx
│ │ │ │ └ AccountForm.tsx
│ │ │ └ hooks/
│ │ │ └ useAccount.ts
│ │ └ product/
│ │ ├ components/
│ │ └ hooks/
│ ├ frontend/
│ │ └ api/
│ │ ├ implement.ts # API呼び出し統括
│ │ └ account/
│ │ └ implement.ts # getAccount, createAccountなど
│ └ styles/
│ └ globals.css
├ swagger/
│ └ openapi.yaml # OpenAPI定義ファイル
├ tsconfig.json
├ next.config.js
└ package.json
3. 各ディレクトリの役割
-
src/app/layout.tsx
アプリ全体共通レイアウト (ヘッダー・フッター・ナビ) -
src/app/
ページごとにフォルダを分け、page.tsx
に画面コンポーネントを配置。
ページ固有のcomponents
,hooks
を同階層にまとめる。 -
src/common/components
全体共通UIコンポーネント (例: Button, Modal) -
src/common/utils
共通ユーティリティ関数 (日付計算、文字列加工) -
src/feature/
ドメイン機能ごとにフォルダを作成し、components
,hooks
をまとめる。 -
src/frontend/api/
-
implement.ts
: 各ドメインAPI呼び出しの統括入口 -
account/implement.ts
:getAccount
,createAccount
などのAPI呼び出しロジック
-
-
swagger/openapi.yaml
API仕様をOpenAPI形式で定義し、自動生成
4. API型定義
Swagger/OpenAPIを使用し、型定義を自動生成し、src/frontend/api/types.ts
などに出力します。
5. 注意事項
- ページ固有のコンポーネント・hooksはページフォルダ内にまとめる。
- レイアウト切り替えは
layout.tsx
で制御。 - ドメイン横断の共通機能は
common
以下に集約。 - API呼び出しはドメインごとに
client
・implement
を分ける。
Discussion