自定义 Webpack 配置
提示:webpack 配置的更改不受 semver 覆盖,请自行承担风险
在继续为应用程序添加自定义 webpack 配置之前,请确保 Next.js 尚未支持你的用例:
一些常用的功能可作为插件使用:
为了扩展我们对 webpack 的使用,你可以在 next.config.js 中定义一个扩展其配置的函数,如下所示:
next.config.js
module.exports = {
webpack: (
config,
{ buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
) => {
// 重要:返回修改后的配置
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 的使用示例:
// 添加依赖于 babel-loader 的加载器的示例配置
// 此源代码来自 @next/mdx 插件源代码:
// 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" 目前仅用于中间件和边缘运行时中的服务端组件。