Next.js + MDXで静的ブログを生成してみる
目標
Next.js + MDXでブログを作り、静的なサイトを出力してみる。
環境
- Macbook Pro (13-inch, 2019, Two Thunderbolt 3 ports)
- CPU: i5-8257u
- RAM: 16GB
- OS: macOS Ventura 13.4
- バージョン
- node: v20.5.0
- next@13.4.13
参考サイト
Next.jsプロジェクトを作成
テンプレートから開始
npm init next-app
✔ What is your project named? … my-app
✔ Would you like to use TypeScript? … Yes
✔ Would you like to use ESLint? … Yes
✔ Would you like to use Tailwind CSS? … No
✔ Would you like to usesrc/directory? … Yes
✔ Would you like to use App Router? (recommended) … Yes
✔ Would you like to customize the default import alias? ... No
静的サイトの作成ではApp Routerの利点は特になさそうだけど、面白そうだから試してみる。
ビルド設定
Static Exportを有効にする。これにより、next build は静的なHTML/CSS/JSを出力するようになる。
/** @type {import('next').NextConfig} */
- const nextConfig = {};
+ const nextConfig = {
+ output: 'export',
+ };
module.exports = nextConfig;
静的生成を試す
ビルド
npm run build

キャッシュ消した状態で24.7秒、2回目は11.8秒
ブラウザで確認
npm run start (next start) を使おうとしたら、代わりにserve を使ってくれと言われたのでそうする。
Error: "next start" does not work with "output: export" configuration. Use "npx serve@latest out" instead.
serveもVercelによるプロジェクトみたい。
ワンライナーとしてはhttp-serverより短くて良さそうかも
せっかくなのでnpm scriptも書き換える
npm i -D serve
"scripts": {
"dev": "next dev",
"build": "next build",
- "start": "next start",
+ "start": "serve out",
"lint": "next lint"
},

無事初期画面が表示された 🎉
MDX
公式に従う
パッケージのインストール
npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdx
@types/* はdevDependenviesに含めないのだろうか...?
src/mdx-components.tsxは公式からコピペして追加
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
+ experimental: {
+ mdxRs: true,
+ },
};
-module.exports = nextConfig;
+const withMDX = require('@next-mdx')()
+module.exports = withMDX(nextConfig);