コンテンツをスキップ

カスタム 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 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

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