Capítulo 426 de 456

webpack (next.config.js option)

Core Idea

Escape hatch to extend Next.js's webpack config directly via a function in next.config.js. Not covered by semver, so changes here carry upgrade risk.

Key Concepts

  • webpack(config, options): function that receives and must return the modified webpack config; executed three times (twice for server: nodejs/edge, once for client).
  • options.isServer: true for server compilation, false for client.
  • options.nextRuntime: "edge" or "nodejs" for server compilation, undefined for client. isServer is true when nextRuntime is either "edge" or "nodejs".
  • options.buildId: unique identifier for the build.
  • options.dev: true in development compilation.
  • options.defaultLoaders.babel: default babel-loader config, useful for chaining custom loaders after it.

Code Examples

module.exports = {
  webpack: (
    config,
    { buildId, dev, isServer, defaultLoaders, nextRuntime, webpack }
  ) => {
    // Important: return the modified config
    return config
  },
}
  • O que demonstra: assinatura completa da função webpack e todos os parâmetros disponíveis.

Anti-patterns

  • Adicionar webpack config antes de checar suporte nativo: CSS imports, CSS modules, Sass/SCSS (imports e modules), babel customization já são suportados nativamente pelo Next.js.

Key Takeaways

  1. Sempre retornar o config modificado, senão o build quebra.
  2. Prefira plugins prontos (@next/mdx, @next/bundle-analyzer) antes de escrever config webpack customizada.
  3. Config de webpack não segue semver; trate mudanças aqui como potencialmente breaking a qualquer minor version.

Connects To

  • turbopack (ch420): alternativa moderna a esta config; Turbopack não usa esta função webpack.