自定义 Webpack 配置
了解如何自定义 Next.js 使用的 webpack 配置
需知:
对 webpack 配置的更改不受 semver 约束,因此请自行承担风险
在继续为你的应用添加自定义 webpack 配置之前,请确认 Next.js 是否已经支持你的用例:
一些常见需求的功能可通过插件获得:
为了扩展我们对 webpack 的使用,你可以在 next.config.js 中定义一个函数来扩展其配置,如下所示:
next.config.jsjs
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 内部使用的默认 loader: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 runtime 中的代理和服务器组件。