Open4

Next.js + MDXで静的ブログを生成してみる

大井さかな大井さかな

Next.jsプロジェクトを作成

テンプレートから開始

shell
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 use src/ 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を出力するようになる。

next.config.js
  /** @type {import('next').NextConfig} */
- const nextConfig = {};
+ const nextConfig = {
+   output: 'export',
+ };
  
  module.exports = nextConfig;
大井さかな大井さかな

静的生成を試す

ビルド

shell
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も書き換える

shell
npm i -D serve
package.json
  "scripts": {
    "dev": "next dev",
    "build": "next build",
-   "start": "next start",
+   "start": "serve out",
    "lint": "next lint"
  },

無事初期画面が表示された 🎉

大井さかな大井さかな

MDX

公式に従う

パッケージのインストール

shell
npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdx

@types/* はdevDependenviesに含めないのだろうか...?

src/mdx-components.tsxは公式からコピペして追加

next.config.js
 /** @type {import('next').NextConfig} */
 const nextConfig = {
   output: 'export',
+  experimental: {
+    mdxRs: true,
+  },
 };
 
-module.exports = nextConfig;
+const withMDX = require('@next-mdx')()
+module.exports = withMDX(nextConfig);