カスタム Webpack 設定

豆知識: webpack 設定の変更は semver の対象外であるため、自己責任で行ってください

アプリケーションにカスタム webpack 設定を追加する前に、Next.js がすでにあなたのユースケースをサポートしていないか確認してください:

よく求められる機能の一部はプラグインとして利用可能です:

webpack の使用を拡張するには、next.config.js 内で設定を拡張する関数を定義します:

next.config.js
module.exports = {
  webpack: (
    config,
    { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
  ) => {
    // 重要: 変更した設定を返す
    return config
  },
}

webpack 関数は3回実行されます。サーバー(nodejs / edge ランタイム)用に2回、クライアント用に1回です。これにより、isServer プロパティを使用してクライアントとサーバーの設定を区別できます。

webpack 関数の第2引数は以下のプロパティを持つオブジェクトです:

  • buildId: String - ビルド間で一意の識別子として使用されるビルド ID
  • dev: Boolean - 開発モードでコンパイルされるかどうかを示す
  • isServer: Boolean - サーバーサイドコンパイルの場合は true、クライアントサイドの場合は false
  • nextRuntime: String | undefined - サーバーサイドコンパイルのターゲットランタイム。"edge" または "nodejs" のいずれかで、クライアントサイドコンパイルの場合は undefined
  • defaultLoaders: Object - Next.js が内部で使用するデフォルトのローダー:
    • babel: Object - デフォルトの babel-loader 設定

defaultLoaders.babel の使用例:

// babel-loader に依存するローダーを追加する設定例
// このソースは @next/mdx プラグインソースから引用:
// https://github.com/vercel/next.js/tree/canary/packages/next-mdx
module.exports = {
  webpack: (config, options) => {
    config.module.rules.push({
      test: /\.mdx/,
      use: [
        options.defaultLoaders.babel,
        {
          loader: '@mdx-js/loader',
          options: pluginOptions.options,
        },
      ],
    })

    return config
  },
}

nextRuntime

nextRuntime"edge" または "nodejs" の場合、isServertrue になります。現在、nextRuntime の "edge" はミドルウェアとエッジランタイムのサーバーコンポーネントのみに使用されます。

On this page