Capítulo 66 de 456

Package Bundling

Core Idea

Analyze and shrink server/client bundles with the Turbopack Bundle Analyzer (next experimental-analyze) or @next/bundle-analyzer for Webpack, then fix large bundles via optimizePackageImports, moving heavy rendering work to Server Components, or serverExternalPackages.

Key Concepts

  • next experimental-analyze: built-in Turbopack bundle analyzer (v16.1+) with import tracing, filterable by route/environment/type; --output writes a static report to .next/diagnostics/analyze.
  • @next/bundle-analyzer: Webpack plugin producing a visual size report per package/dependency.
  • optimizePackageImports: next.config.js option that loads only the modules actually used from packages with many named exports (icon/utility libraries), even with barrel-style imports. Some libraries are optimized automatically without needing the list.
  • serverExternalPackages: opts specific packages out of automatic server-side bundling (for Server Components/Route Handlers, which are bundled by default).
  • Heavy client workloads: expensive data-to-UI transform libraries (syntax highlighting, charts, markdown) should run in a Server Component instead of shipping the whole library to the client.

Code Examples

npx next experimental-analyze
npx next experimental-analyze --output
  • O que demonstra: roda o analyzer interativo do Turbopack, ou grava o relatório em disco pra comparar antes/depois.
const nextConfig = {
  experimental: {
    optimizePackageImports: ['icon-library'],
  },
}
module.exports = nextConfig
  • O que demonstra: tree-shaking automático para libs de muitos exports.
import { codeToHtml } from 'shiki'

export default async function Page() {
  const code = `export function hello() { console.log("hi") }`
  const highlightedHtml = await codeToHtml(code, { lang: 'tsx', theme: 'github-dark' })
  return (
    <article>
      <pre><code dangerouslySetInnerHTML={{ __html: highlightedHtml }} /></pre>
    </article>
  )
}
  • O que demonstra: mover highlighting (antes um 'use client' com prism-react-renderer) para Server Component com Shiki, cliente recebe só markup estático.
const nextConfig = {
  serverExternalPackages: ['package-name'],
}
module.exports = nextConfig
  • O que demonstra: exclui um pacote específico do bundling automático no servidor.

Anti-patterns

  • Fazer highlighting/parsing/chart-rendering em Client Component sem necessidade de API de browser: embarca a lib inteira no bundle do cliente; mova para Server Component quando não precisa de interatividade.

Key Takeaways

  1. Next.js já faz code-splitting e tree-shaking automáticos; a análise manual é para casos que sobram.
  2. optimizePackageImports resolve o problema de "import nomeado de lib gigante" sem mudar o jeito de importar.
  3. Trabalho pesado de transformação de dados em UI deve rodar no servidor sempre que não depender de browser APIs ou interação.
  4. @next/bundle-analyzer exige ANALYZE=true npm run build; o novo analyzer do Turbopack roda direto via next experimental-analyze.

Connects To

  • production: bundle analysis é um item do checklist antes de produção.
  • lazy-loading: outra técnica citada para reduzir bundle inicial.