コンテンツにスキップ

カスタムWebpack設定

知っておくと良いこと: webpack設定の変更はsemverの対象外であるため、自己責任で進めてください

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

よく求められる機能のいくつかは、プラグインとして利用可能です

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

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

webpack関数は3回実行されます。サーバー(Node.js / 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の使用例

// 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

nextRuntime"edge"または"nodejs"の場合、isServertrueであることに注意してください。nextRuntime"edge"は、現在ミドルウェアおよびEdgeランタイムでのサーバーコンポーネント専用です。