Custom Webpack Config
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:
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, webpack }) => {
// Note: we provide webpack above so you should not `require` it
// Perform customizations to webpack config
config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
// Important: return the modified config
return config
},
}
The
webpack
function is executed twice, once for the server and once for the client. This allows you to distinguish between client and server configuration using theisServer
property.
The second argument to the webpack
function is an object with the following properties:
buildId
:String
- The build id, used as a unique identifier between buildsdev
:Boolean
- Indicates if the compilation will be done in developmentisServer
:Boolean
- It’strue
for server-side compilation, andfalse
for client-side compilationdefaultLoaders
:Object
- Default loaders used internally by Next.js:babel
:Object
- Defaultbabel-loader
configuration
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
},
}
Related
[
Introduction to next.config.js
Learn more about the configuration file used by Next.js.]($0b4bd5a3a6817758.md)