はじめに
Next.jsのApp Routerで最小構成のHello Worldアプリを作成してみます。
App Router
App RouterはNext.js 13.4から安定版になった新しいルーティング機能で、従来の方法はPages Routerと呼ばれています。
Pages Routerも使えるようになっていますが、新しくアプリを作る場合はApp Routerを使うことが推奨されているようです。
App Router | Next.js
UsethenewAppRouterwithNext.js'andReact'slatestfeatures,includingLayouts,ServerComponents,Suspense,andmore.
ディレクトリ構造
Typescriptで最小のApp Routerを使った場合は下記のようになります。
.
├── app/
│ ├── layout.tsx
│ └── page.tsx
├── next-env.d.ts
├── node_modules/
├── package-lock.json
├── package.json
└── tsconfig.json
App Routerで使われるディレクトリとファイルは下記のようなものが含まれます。
app/
: App Router用ディレクトリlayout.tsx
: ルート共通のレイアウトpage.tsx
: ルート固有のUI
他にもnot-found.tsx
やerror.tsx
でNot Found UIやError UIを定義することができます。また、app/folder
としてネストしたルートも作成可能です。
Getting Started: Project Structure | Next.js
AlistoffoldersandfilesconventionsinaNext.jsproject
Hello Worldアプリを作ってみる
それでは、create-next-app
を使わず手動で最小構成のHello Worldアプリを作ってみます。
ディレクトリ構成は下記の通りです。
.
├── app/
│ ├── layout.tsx
│ └── page.tsx
├── next-env.d.ts
├── node_modules/
├── package-lock.json
├── package.json
└── tsconfig.json
まずは、必要なパッケージをインストールします。
npm install next@latest react@latest react-dom@latest
次にpackage.json
にNext.js用のスクリプトを追加します。
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "^13.4.10",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
App Routerのapp
ディレクトリとlayout.tsx
とpage.tsx
を作成します。
mkdir app
.
└── app
├── layout.tsx
└── page.tsx
layout.tsx
にはRoot Layoutを定義します。Root Layoutは全てのページに適用されるレイアウトになります。
Routing: Pages and Layouts | Next.js
CreateyourfirstpageandsharedlayoutwiththeAppRouter.
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="ja">
<body>{children}</body>
</html>
)
}
最後にpage.tsx
でホームとなるページを定義します。
export default function Page() {
return <h1>Hello World</h1>
}
下記のコマンドで実行すると、localhost:3000
でアプリにアクセスできます。
npm run dev