跳到主要內容

自訂 Webpack 設定

須知事項:對 webpack 設定的變更不受語意化版本控制的約束,請自行承擔風險

在繼續將自訂 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 函式會執行三次,伺服器端 (nodejs / edge runtime) 執行兩次,用戶端執行一次。這可讓您使用 isServer 屬性來區分用戶端和伺服器端設定。

webpack 函式的第二個引數是一個物件,具有下列屬性

  • buildId字串 - 建置 ID,用作建置之間的唯一識別碼。
  • dev布林值 - 指出是否將在開發環境中完成編譯。
  • isServer布林值 - 伺服器端編譯為 true,用戶端編譯為 false
  • nextRuntime字串 | undefined - 伺服器端編譯的目標執行階段;為 "edge""nodejs",用戶端編譯則為 undefined
  • defaultLoaders物件 - Next.js 內部使用的預設載入器
    • babel物件 - 預設 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" 時,isServertruenextRuntime "edge" 目前僅適用於中介層和 edge runtime 中的伺服器組件。