自定义 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 theisServer
property.
webpack
函数的第二个参数是具有以下属性的对象:
¥The second argument to the webpack
function is an object with the following properties:
-
buildId
:String
- 构建 ID,用作构建之间的唯一标识符。¥
buildId
:String
- The build id, used as a unique identifier between builds. -
dev
:Boolean
- 指示是否将在开发中完成编译。¥
dev
:Boolean
- Indicates if the compilation will be done in development. -
isServer
:Boolean
- 它是用于服务器端编译的true
,用于客户端编译的false
。¥
isServer
:Boolean
- It'strue
for server-side compilation, andfalse
for client-side compilation. -
nextRuntime
:String | undefined
- 服务器端编译的目标运行时;无论是"edge"
还是"nodejs"
,客户端编译都是undefined
。¥
nextRuntime
:String | undefined
- The target runtime for server-side compilation; either"edge"
or"nodejs"
, it'sundefined
for client-side compilation. -
defaultLoaders
:Object
- Next.js 内部使用的默认加载器:¥
defaultLoaders
:Object
- Default loaders used internally by Next.js:-
babel
:Object
- 默认babel-loader
配置。¥
babel
:Object
- Defaultbabel-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"
时,isServer
是 true
,nextRuntime
"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.