Capítulo 449 de 456

Next.js Compiler

Core Idea

The Next.js Compiler is a Rust-based compiler built on SWC that transforms/minifies JS for production, replacing Babel (per-file transforms) and Terser (bundle minification). ~17x faster than Babel, enabled by default since v12; auto-disabled (falls back to Babel) if a .babelrc file is detected.

Key Concepts

  • compiler.styledComponents: ports babel-plugin-styled-components; boolean or object (displayName, ssr, fileName, topLevelImportPaths, meaninglessFileNames, minify, transpileTemplateLiterals, namespace, pure, cssProp).
  • compiler.relay: enables Relay support (src, artifactDirectory, language, eagerEsModules); must set artifactDirectory outside pages/ to avoid generated files becoming routes.
  • compiler.reactRemoveProperties: removes JSX props matching a regex (default ^data-test), useful for stripping test attributes; custom regex via { properties: [...] } (Rust regex syntax, not JS).
  • compiler.removeConsole: strips console.* calls from app code (not node_modules); { exclude: ['error'] } keeps console.error.
  • compiler.emotion: ports @emotion/babel-plugin; boolean or object (sourceMap, autoLabel, labelFormat, importMap).
  • compiler.define/compiler.defineServer: statically replace variables at build time; define applies to all environments, defineServer only to server/edge code.
  • compiler.runAfterProductionCompile: lifecycle hook running after production compilation, before type-checking/static generation; receives { distDir, projectDir }, useful for collecting sourcemaps.
  • Legacy Decorators / jsxImportSource: auto-detected from experimentalDecorators/jsxImportSource in tsconfig.json/jsconfig.json.
  • next/jest: transpiles tests, auto-mocks CSS/image imports, sets up SWC transform, loads .env, ignores node_modules/.next.
  • Minification: SWC-based since v13, 7x faster than Terser; not customizable since v15 (swcMinify flag removed).
  • transpilePackages: replaces next-transpile-modules.
  • Experimental: swcTraceProfiling, swcPlugins: generate Chromium trace event traces; load wasm-based SWC plugins by npm package name or absolute .wasm path.

Code Examples

module.exports = {
  compiler: {
    removeConsole: {
      exclude: ['error'],
    },
  },
}
  • O que demonstra: remove todos console.* de produção exceto console.error.
const nextJest = require('next/jest')
const createJestConfig = nextJest({ dir: './' })
const customJestConfig = { setupFilesAfterEnv: ['<rootDir>/jest.setup.js'] }
module.exports = createJestConfig(customJestConfig)
  • O que demonstra: integração padrão do Jest com o Next.js Compiler via next/jest.
module.exports = {
  compiler: {
    define: { MY_VARIABLE: 'my-string', 'process.env.MY_ENV_VAR': 'my-env-var' },
    defineServer: { MY_SERVER_VARIABLE: 'my-server-var' },
  },
}
  • O que demonstra: substitui variáveis estaticamente no build; defineServer só afeta código server/edge.

Reference Tables

VersionChanges
v13.1.0Module Transpilation e Modularize Imports estáveis.
v13.0.0SWC Minifier habilitado por padrão.
v12.3.0SWC Minifier estável.
v12.2.0Suporte experimental a SWC Plugins.
v12.1.0Styled Components, Jest, Relay, Remove React Properties, etc.
v12.0.0Next.js Compiler introduzido.

Anti-patterns

  • Ter um .babelrc sem necessidade real: desativa silenciosamente o Next.js Compiler para todos os arquivos, perdendo a velocidade do SWC.
  • Setar artifactDirectory do Relay dentro de pages/: o arquivo gerado vira uma rota e quebra o build de produção.

Key Takeaways

  1. modularizeImports foi superseded por optimizePackageImports (Next.js 13.5+).
  2. Regex de reactRemoveProperties usa sintaxe Rust (regex crate), diferente de RegExp do JS.
  3. Presença de config Babel força fallback total pro Babel; não há mix seletivo.

Connects To

  • transpilePackages (ch419): mesma feature descrita aqui sob "Module Transpilation".
  • ESLint (ch429): linting complementar ao compiler, mas peça separada.