Next.jsのAppRouter機能を用いた静的サイトの作成
に公開
Next.js 13.3からApp Router機能が静的エクスポート(next export)に対応しました。

こちらは、以下のスクラップをまとめたものです。
TL;DR
create-next-appを用いてアプリケーションのテンプレートを作成- 静的出力のオプションを有効化
- pagesディレクトリとAPI Routeを削除
- ビルド
Next.jsのアプリケーションを作成
アプリケーションテンプレートを作成
create-next-appを用いてアプリケーションのテンプレートを作成
$ npx create-next-app@latest
app/ディレクトリのオプションを有効化する
Need to install the following packages: create-next-app@13.3.0 Ok to proceed? (y) y ✔ What is your project named? … nextjs-demo ✔ Would you like to use TypeScript with this project? … No / Yes ✔ Would you like to use ESLint with this project? … No / Yes ✔ Would you like to use Tailwind CSS with this project? … No / Yes ✔ Would you like to use `src/` directory with this project? … No / Yes ✔ Would you like to use experimental `app/` directory with this project? … No / Yes ✔ What import alias would you like configured? … @/* Creating a new Next.js app in /Users/ryohidaka/nextjs-demo.
静的出力のオプションを有効化
ドキュメントに倣ってnext.config.jsを修正。
:::message
ドキュメントにはappDir: trueの記述はないが、含めないとエラーが発生するので注意
Error: > The
appdirectory is experimental. To enable, addappDir: trueto yournext.config.jsconfiguration underexperimental. See
:::
/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { appDir: true, }, // @see https://beta.nextjs.org/docs/configuring/static-export#configuration output: "export", }; module.exports = nextConfig
pagesディレクトリとAPI Routeを削除
初期生成ファイルにpages/api/hello.tsが含まれてているため削除する。
error - API Routes cannot be used with "output: export". See more info here:
また、pagesディレクトリが存在する場合、appディレクトリと競合して404エラーになるため、pagesディレクトリごと削除する。
動作確認
ホットリロードで実行できるか確認
next devを実行し、Next.jsのデフォルトページが表示できることを確認

ビルド
静的出力を行う。
Deploying With a static export, Next.js can be deployed and hosted on any web server that can serve HTML/CSS/JS > static assets.
When running next build, Next.js generates the static export into the out folder. Using next export is no longer needed. For example, let's say you have the following > routes:
以前はnext build && next exportのようにビルドした上で静的出力する対応が必要だったが、Next.js13.3からはnext buildだけでoutディレクトリに出力してくれるようになったらしい。
無事出力処理が行われ、outディレクトリ以下に展開されたることを確認

