自訂 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
: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"
時,isServer
為 true
,nextRuntime
"edge"
目前僅適用於中介軟體和邊緣執行階段中的伺服器元件。
這有幫助嗎?