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:

  1. module.exports = {
  2. webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
  3. // Note: we provide webpack above so you should not `require` it
  4. // Perform customizations to webpack config
  5. config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
  6. // Important: return the modified config
  7. return config
  8. },
  9. }

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 the isServer 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 builds
  • dev: Boolean - Indicates if the compilation will be done in development
  • isServer: Boolean - It’s true for server-side compilation, and false for client-side compilation
  • defaultLoaders: Object - Default loaders used internally by Next.js:
    • babel: Object - Default babel-loader configuration

Example usage of defaultLoaders.babel:

  1. // Example config for adding a loader that depends on babel-loader
  2. // This source was taken from the @next/mdx plugin source:
  3. // https://github.com/vercel/next.js/tree/canary/packages/next-mdx
  4. module.exports = {
  5. webpack: (config, options) => {
  6. config.module.rules.push({
  7. test: /\.mdx/,
  8. use: [
  9. options.defaultLoaders.babel,
  10. {
  11. loader: '@mdx-js/loader',
  12. options: pluginOptions.options,
  13. },
  14. ],
  15. })
  16. return config
  17. },
  18. }

Related

[

Introduction to next.config.js

Learn more about the configuration file used by Next.js.]($0b4bd5a3a6817758.md)