コンテンツにスキップ

Custom Webpack Config

注意: webpack設定の変更はsemverの対象外となるため、自己責任で実行してください。

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

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

webpack の使用を拡張するには、次のように next.config.js 内で config を拡張する関数を定義できます。

next.config.js
module.exports = {
  webpack: (
    config,
    { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
  ) => {
    // Important: return the modified config
    return config
  },
}

webpack 関数は3回実行されます。サーバー(nodejs / edge runtime)用に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 の使用例

// Example config for adding a loader that depends on babel-loader
// This source was taken from the @next/mdx plugin source:
// 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

isServer"edge" または "nodejs" の場合に true になることに注意してください。"edge" は現在、edgeランタイムのプロキシとServer Components専用です。