【Typescript】Next.jsのApp Routerで最小のHello Worldを作成してみる

スポンサーリンク

はじめに

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.tsxerror.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.tsxpage.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

参考

タイトルとURLをコピーしました