Skip to main content

自定义 Webpack 配置

很高兴知道:semver 不涵盖对 webpack 配置的更改,因此请自行承担风险

¥Good to know: changes to webpack config are not covered by semver so proceed at your own risk

在继续将自定义 webpack 配置添加到你的应用之前,请确保 Next.js 尚不支持你的用例:

¥Before continuing to add custom webpack configuration to your application make sure Next.js doesn't already support your use-case:

一些常见的功能可以作为插件提供:

¥Some commonly asked for features are available as plugins:

为了扩展 webpack 的使用,你可以定义一个在 next.config.js 内部扩展其配置的函数,如下所示:

¥In order to extend our usage of webpack, you can define a function that extends its config inside next.config.js, like so:

module.exports = {
webpack: (
config,
{ buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
) => {
// Important: return the modified config
return config
},
}

webpack 函数执行了 3 次,两次为服务器(nodejs/edge 运行时)执行一次,一次为客户端执行。这允许你使用 isServer 属性区分客户端和服务器配置。

¥The webpack function is executed three times, twice for the server (nodejs / edge runtime) and once for the client. This allows you to distinguish between client and server configuration using the isServer property.

webpack 函数的第二个参数是具有以下属性的对象:

¥The second argument to the webpack function is an object with the following properties:

  • buildIdString - 构建 ID,用作构建之间的唯一标识符。

    ¥buildId: String - The build id, used as a unique identifier between builds.

  • devBoolean - 指示是否将在开发中完成编译。

    ¥dev: Boolean - Indicates if the compilation will be done in development.

  • isServerBoolean - 它是用于服务器端编译的 true,用于客户端编译的 false

    ¥isServer: Boolean - It's true for server-side compilation, and false for client-side compilation.

  • nextRuntimeString | undefined - 服务器端编译的目标运行时;无论是 "edge" 还是 "nodejs",客户端编译都是 undefined

    ¥nextRuntime: String | undefined - The target runtime for server-side compilation; either "edge" or "nodejs", it's undefined for client-side compilation.

  • defaultLoadersObject - Next.js 内部使用的默认加载器:

    ¥defaultLoaders: Object - Default loaders used internally by Next.js:

    • babelObject - 默认 babel-loader 配置。

      ¥babel: Object - Default babel-loader configuration.

defaultLoaders.babel 的用法示例:

¥Example usage of 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" 目前仅适用于边缘运行时中的中间件和服务器组件。

¥Notice that isServer is true when nextRuntime is "edge" or "nodejs", nextRuntime "edge" is currently for middleware and Server Components in edge runtime only.