自訂 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 執行環境),一次用於客戶端。這讓您可以使用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
" 目前僅適用於 edge 執行環境中的中間件和伺服器組件。
這有幫助嗎?