静的エクスポート (Static Exports)

Next.jsでは静的サイトやシングルページアプリケーション (SPA) として開始し、後からサーバーが必要な機能にオプションでアップグレードできます。

next buildを実行すると、Next.jsはルートごとにHTMLファイルを生成します。厳密なSPAを個別のHTMLファイルに分割することで、Next.jsはクライアントサイドで不要なJavaScriptコードの読み込みを回避し、バンドルサイズを削減してページ読み込みを高速化できます。

Next.jsはこの静的エクスポートをサポートしているため、HTML/CSS/JS静的アセットを提供できる任意のWebサーバーにデプロイしてホストできます。

知っておくと便利: 静的エクスポートの強化されたサポートにはApp Routerの使用を推奨します。

設定

静的エクスポートを有効にするには、next.config.js内で出力モードを変更します:

next.config.js
/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  output: 'export',

  // オプション: リンク `/me` -> `/me/` に変更し、`/me.html` -> `/me/index.html` を生成
  // trailingSlash: true,

  // オプション: 自動的な `/me` -> `/me/` 変換を防止し、`href`を保持
  // skipTrailingSlashRedirect: true,

  // オプション: 出力ディレクトリを `out` -> `dist` に変更
  // distDir: 'dist',
}

module.exports = nextConfig

next buildを実行後、Next.jsはアプリケーションのHTML/CSS/JSアセットを含むoutフォルダを生成します。

getStaticPropsgetStaticPaths を使用して、pagesディレクトリ内の各ページ(または動的ルートの場合はさらに多くのページ)のHTMLファイルを生成できます。

サポートされる機能

静的サイトを構築するために必要なNext.jsの主要機能のほとんどがサポートされています:

画像最適化

next/imageによる画像最適化は、next.config.jsでカスタム画像ローダーを定義することで静的エクスポートで使用できます。例えば、Cloudinaryのようなサービスで画像を最適化できます:

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',
  images: {
    loader: 'custom',
    loaderFile: './my-loader.ts',
  },
}

module.exports = nextConfig

このカスタムローダーは、リモートソースから画像を取得する方法を定義します。例えば、次のローダーはCloudinaryのURLを構築します:

export default function cloudinaryLoader({
  src,
  width,
  quality,
}: {
  src: string
  width: number
  quality?: number
}) {
  const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`]
  return `https://res.cloudinary.com/demo/image/upload/${params.join(
    ','
  )}${src}`
}
export default function cloudinaryLoader({ src, width, quality }) {
  const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`]
  return `https://res.cloudinary.com/demo/image/upload/${params.join(
    ','
  )}${src}`
}

その後、アプリケーションでnext/imageを使用し、Cloudinary内の画像への相対パスを定義できます:

import Image from 'next/image'

export default function Page() {
  return <Image alt="カメ" src="/turtles.jpg" width={300} height={300} />
}
import Image from 'next/image'

export default function Page() {
  return <Image alt="カメ" src="/turtles.jpg" width={300} height={300} />
}

サポートされない機能

Node.jsサーバーを必要とする機能や、ビルドプロセス中に計算できない動的ロジックはサポートされていません:

デプロイ

静的エクスポートでは、Next.jsはHTML/CSS/JS静的アセットを提供できる任意のWebサーバーにデプロイしてホストできます。

next buildを実行すると、Next.jsは静的エクスポートをoutフォルダに生成します。next exportはもはや必要ありません。例えば、次のルートがあるとします:

  • /
  • /blog/[id]

next build実行後、Next.jsは次のファイルを生成します:

  • /out/index.html
  • /out/404.html
  • /out/blog/post-1.html
  • /out/blog/post-2.html

Nginxのような静的ホストを使用している場合、受信リクエストから正しいファイルへのリライトを設定できます:

nginx.conf
server {
  listen 80;
  server_name acme.com;

  root /var/www/out;

  location / {
      try_files $uri $uri.html $uri/ =404;
  }

  # `trailingSlash: false`の場合に必要
  # `trailingSlash: true`の場合は省略可能
  location /blog/ {
      rewrite ^/blog/(.*)$ /blog/$1.html break;
  }

  error_page 404 /404.html;
  location = /404.html {
      internal;
  }
}

バージョン履歴

バージョン変更内容
v13.4.0App Router(安定版)が強化された静的エクスポートサポートを追加、Reactサーバーコンポーネントとルートハンドラーの使用を含む
v13.3.0next exportが非推奨となり、"output": "export"に置き換えられました