跳到内容

自定义 Webpack 配置

须知:webpack 配置的更改不受 semver 约束,请自行承担风险

在继续向你的应用添加自定义 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" 时,isServertruenextRuntime "edge" 目前仅用于中间件和 Edge Runtime 中的服务器组件。