Next.js course ยท Module 1: Next.js Configuration

Turbopack and Compilation Optimization

12 min read ยท
In this lesson14

At the heart of Quantum Metropolis, a powerful energy generator called TurboCore operates, powering the entire city far more efficiently than outdated reactors. Similarly, the Next.js world gained a new bundling engine - Turbopack - which became the default bundler in Next.js 16 and is revolutionizing the compilation speed of web applications.

What is Turbopack?

Turbopack is a modern bundler written in Rust, created by the authors of Next.js and Webpack. It was designed with maximum performance and scalability in mind, especially for large applications.

Unlike older tools, Turbopack:

  • Compiles only the required elements, not the entire application
  • Uses intelligent caching to avoid unnecessary recalculations
  • Works much faster than Webpack, especially in development mode

Turbopack in a Next.js 16 Project - On by Default

In Quantum Metropolis, new buildings are connected to the TurboCore energy network from day one, and a single switch moves them back to the old grid. Similarly, in Next.js 16 Turbopack works right away and needs no flag at all:

# Development server - Turbopack by default
npx next dev

# Switch back to Webpack (only if your project needs it)
npx next dev --webpack

In package.json, the scripts no longer need the --turbo or --turbopack flag that switched Turbopack on in Next.js 15:

{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  }
}

Then simply run:

npm run dev
# or
yarn dev

Advantages of Turbopack

1. Lightning-fast Compilation Times

Just as TurboCore in Quantum Metropolis delivers energy almost instantly, Turbopack drastically reduces compilation time:

  • 2-5x faster production builds (next build) - according to the Next.js team at the Next.js 16 release
  • Up to 10x faster Fast Refresh (HMR) for component changes
  • Disk cache - since Next.js 16.1 for next dev and since 16.3 for next build too, which makes restarts even faster

2. Selective Compilation and Intelligent Caching

Turbopack analyzes the application's dependency structure and compiles only the parts that are actually needed. It's like an intelligent energy system in the Metropolis that directs energy only where it's currently required.

// Turbopack will compile only this component and its dependencies,
// if it is currently used in the application
export default function QuantumNavigation() {
  return (
    <div className="p-4 bg-gradient-to-r from-indigo-500 to-purple-600 rounded-lg">
      <h2 className="text-xl font-semibold text-white">Quantum Navigation System</h2>
      <p className="text-white/80">
        Choose a destination in the solar system
      </p>
      {/* ... */}
    </div>
  );
}

3. Incremental Compilation

When code changes, Turbopack recompiles only the files that were changed and those that directly depend on them. Just like in Quantum Metropolis, where modernizing one system doesn't require restarting the entire city.

Compatibility with Next.js 16

In Next.js 16, Turbopack is stable and the default for both next dev and next build. In Next.js 15 only development mode was stable, and production builds reached beta only in Next.js 15.5. Here are the supported features:

  • app Directory (App Router)
  • Compatibility with developer tools (HMR, Fast Refresh)
  • Support for import aliases and jsconfig.json/tsconfig.json
  • Support for environment variables (.env)
  • Support for CSS Modules and Global CSS
  • Support for Tailwind CSS
  • Proxy (proxy.ts, called middleware.ts in older versions)
  • Support for API Routes
  • Support for Sass, PostCSS and React Server Components

Turbopack does not support Webpack plugins or a webpack() function in next.config, though: projects that need them run with the --webpack flag.

Benchmarking and Performance - Metropolis TurboCore Data

Just as engineers in Quantum Metropolis conduct performance tests on the new TurboCore system, we can measure Turbopack's performance in our project. The numbers below are examples: the real gain depends on the project, so always measure it on your own application.

OperationWebpackTurbopackImprovement
Cold start40s2.2s~18x faster
Rebuild (component)180ms15ms~12x faster
Rebuild (page)300ms25ms~12x faster
Rebuild (CSS)160ms10ms~16x faster

Turbopack Optimization and Troubleshooting

Turbopack Performance Diagnostics

Turbopack has built-in diagnostic tools. If compilation slows down, record a trace of what the bundler is doing:

# Record a trace of Turbopack while the development server runs
npm run dev -- --internal-trace

# After stopping the server, open the saved file in the trace viewer
npx next internal trace .next-profiles/trace-turbopack.bin

You'll then see exact information about what's happening during compilation, similar to energy diagnostics in Quantum Metropolis. The second command starts a local trace server, and you view the chart itself at trace.nextjs.org.

Bundle Size Analysis

To monitor bundle size, Next.js 16 gives you two tools. With Turbopack, the default bundler, use the built-in analyzer, available as an experimental feature since Next.js 16.1:

npx next experimental-analyze

It opens an interactive view of your modules, where you filter by route and check why a given module ended up in the bundle. The classic @next/bundle-analyzer plugin, on the other hand, works only with Webpack:

npm install --save-dev @next/bundle-analyzer

Configuration in next.config.js:

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
});

/** @type {import('next').NextConfig} */
const nextConfig = {
  // Other configuration options...
};

module.exports = withBundleAnalyzer(nextConfig);

Running the analysis:

ANALYZE=true npx next build --webpack

The --webpack flag is required here: without it, next build uses Turbopack, detects the Webpack configuration added by the plugin and fails.

Common Turbopack Issues and Solutions

ProblemSolution
Lack of support for some Webpack loadersConfigure the loader in the turbopack.rules option in next.config, or check the Turbopack documentation for an alternative
Webpack plugins (Turbopack does not support them)Look for a Turbopack-compatible alternative, or run next dev and next build with the --webpack flag
HMR issues in large projectsSplit code into smaller modules and use lazy loading

Compilation Optimization Strategies Beyond Turbopack

Even if you're using Turbopack, there are additional compilation optimization strategies in Next.js 16:

1. Code Splitting and Lazy Loading

Just as Quantum Metropolis distributes resources on demand, you can use lazy loading of components in Next.js 16:

// components/GalaxyMapLazy.tsx
"use client";

import dynamic from 'next/dynamic';

// Lazy loading the map component, which can be heavy
const InteractiveGalaxyMap = dynamic(
  () => import('@/components/InteractiveGalaxyMap'),
  {
    loading: () => <div className="h-96 bg-gray-200 animate-pulse rounded-lg" />,
    ssr: false, // Disabling SSR works only in a Client Component
  }
);

export default InteractiveGalaxyMap;

The page stays a Server Component and imports the ready, lazily loaded component (ssr: false written in a Server Component is a build error):

// app/exploration/page.tsx
import { Suspense } from 'react';
import InteractiveGalaxyMap from '@/components/GalaxyMapLazy';

export default function ExplorationPage() {
  return (
    <div className="container mx-auto py-8">
      <h1 className="text-3xl font-bold mb-6">Galaxy Exploration</h1>

      <div className="prose max-w-none mb-8">
        <p>Choose your destination in our interactive galaxy map...</p>
      </div>

      <Suspense fallback={<div className="h-96 bg-gray-200 animate-pulse rounded-lg" />}>
        <InteractiveGalaxyMap />
      </Suspense>
    </div>
  );
}

2. Import Optimization

In Quantum Metropolis, energy transporters are optimized to carry energy along the shortest possible path. Similarly, you can optimize imports in your code:

// Bad import - imports all of lodash
import _ from 'lodash';

// Also a bad import - the lodash package (CommonJS) still ends up in the bundle in full
import { debounce, throttle } from 'lodash';

// Good import - imports specific functions from submodules
import debounce from 'lodash/debounce';
import throttle from 'lodash/throttle';

3. Micro-frontends and Modular Build Optimization

Just as Quantum Metropolis is divided into autonomous sectors that can be improved independently, you can consider a modular approach:

quantum-voyages/
  โ”œโ”€โ”€ main/               # Main Next.js application
  โ”œโ”€โ”€ modules/
  โ”‚   โ”œโ”€โ”€ bookings/       # Booking module (independent application)
  โ”‚   โ”œโ”€โ”€ destinations/   # Destinations module (independent application)
  โ”‚   โ””โ”€โ”€ profiles/       # User profiles module (independent application)
  โ””โ”€โ”€ shared/
      โ””โ”€โ”€ ui-components/  # Shared UI components

4. Image and Static Asset Optimization

Just as Quantum Metropolis optimizes visual data transmission, you can optimize your images:

// Using optimized Image component from Next.js
import Image from 'next/image';

export default function DestinationGallery() {
  return (
    <div className="grid grid-cols-3 gap-4">
      <div className="relative h-48">
        <Image
          src="/images/mars-colony.jpg"
          alt="Mars Colony"
          fill
          sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
          className="object-cover rounded-lg"
          loading="lazy"
        />
      </div>
      {/* ... more images ... */}
    </div>
  );
}

Monitoring Compilation Performance

Just as engineers in Quantum Metropolis constantly monitor TurboCore system performance, you can monitor your compilation performance. In Next.js 16 you do not need to enable anything: next dev shows the compile time (Compile) and render time (Render) of every request in the terminal, and next build reports the time of each build step:

npm run build

# Example output in Next.js 16:
#    โ–ฒ Next.js 16 (Turbopack)
#  โœ“ Compiled successfully in 615ms
#  โœ“ Finished TypeScript in 1114ms
#  โœ“ Collecting page data in 208ms
#  โœ“ Generating static pages in 239ms
#  โœ“ Finalizing page optimization in 5ms

For more advanced monitoring, you can use CI/CD tool plugins that track build times in each iteration.

Turbopack - The Future

Just as TurboCore in Quantum Metropolis undergoes constant improvements, Turbopack is actively developed with the future in mind:

  • Full support for all Next.js features
  • Expanded plugin and loader ecosystem
  • Greater compatibility with existing tools and libraries
  • Even faster compilation times and lower memory usage

When NOT to Use Turbopack?

Despite all its advantages, sometimes TurboCore in Quantum Metropolis is not used in some older city sectors due to compatibility issues. Similarly, there are situations where it's better to stick with Webpack:

  • When you use Webpack plugins or loaders that are not yet supported by Turbopack
  • When your application has a specific build configuration that is not supported by Turbopack
  • When next.config contains a custom webpack() function: in Next.js 16, next build with such a configuration fails until you move it to Turbopack options or add the --webpack flag

Developer Tools and Plugins to Speed Up Work

Just as Quantum Metropolis engineers use advanced tools to work with TurboCore, we can also streamline our workflow:

  • VSCode Extension for Next.js: Suggestions, navigation, and syntax highlighting
  • ESLint: Instant feedback on potential issues
  • TypeScript: Error detection at compile time
  • Prettier: Automatic code formatting

Design Practices Supporting Efficient Compilation

Quantum Metropolis Structure

Quantum Metropolis architects designed the city in a modular way - we can design our application the same way:

  1. Organize code by functionality:
app/
  โ”œโ”€โ”€ (auth)/               # Logical grouping for auth features
  โ”‚   โ”œโ”€โ”€ login/
  โ”‚   โ””โ”€โ”€ register/
  โ”œโ”€โ”€ (main)/               # Main functionality
  โ”‚   โ”œโ”€โ”€ dashboard/
  โ”‚   โ””โ”€โ”€ settings/
  โ””โ”€โ”€ (bookings)/           # Booking functionality
      โ”œโ”€โ”€ destinations/
      โ””โ”€โ”€ checkout/
  1. Design components with performance in mind:
// components/ui/QuantumButton.tsx
import { ButtonHTMLAttributes, forwardRef } from 'react';
import { cva, type VariantProps } from 'class-variance-authority';

// Defining button variants with Tailwind CSS
const buttonVariants = cva(
  "relative inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors",
  {
    variants: {
      variant: {
        default: "bg-blue-600 text-white hover:bg-blue-700",
        destructive: "bg-red-600 text-white hover:bg-red-700",
        outline: "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
        secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline",
      },
      size: {
        default: "h-10 px-4 py-2",
        sm: "h-9 rounded-md px-3",
        lg: "h-11 rounded-md px-8",
        icon: "h-10 w-10",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
);

export interface ButtonProps
  extends ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof buttonVariants> {}

const QuantumButton = forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, ...props }, ref) => {
    return (
      <button
        className={buttonVariants({ variant, size, className })}
        ref={ref}
        {...props}
      />
    );
  }
);
QuantumButton.displayName = "QuantumButton";

export { QuantumButton, buttonVariants };

Practical Example of Speeding Up the Quantum Voyages Project Compilation

Imagine we have a large Quantum Voyages project with many components and pages that compiles slowly. Here's how we'll optimize it:

  1. Make sure Turbopack is running - it is the default in Next.js 16, so just start the server without the --webpack flag:
npm run dev
  1. Optimize imports:
// components/ui/Dashboard.tsx

// Before optimization
import _ from 'lodash';

// After optimization - import only the function we need
import debounce from 'lodash/debounce';
  1. Lazy load heavy components:
// components/maps/QuantumMap3DLazy.tsx - Client Component
"use client";

import dynamic from 'next/dynamic';

// Heavy 3D map component loaded lazily
const QuantumMap3D = dynamic(() => import('@/components/maps/QuantumMap3D'), {
  loading: () => <p>Loading quantum map...</p>,
  ssr: false,
});

export default QuantumMap3D;

The app/destinations/page.tsx page stays a Server Component and only imports QuantumMap3DLazy.

  1. Modularize the application:
// Split large files into smaller ones, focused on specific tasks
// bookings/BookingForm.tsx -> split into:
// - bookings/components/PassengerDetails.tsx
// - bookings/components/DestinationPicker.tsx
// - bookings/components/DateSelection.tsx
// - bookings/components/PaymentForm.tsx

Summary

Just as TurboCore revolutionized energy delivery in Quantum Metropolis, Turbopack changes the way we compile Next.js 16 applications. Thanks to it:

  1. You significantly speed up the development cycle
  2. You save resources through selective compilation
  3. You get a more performant application through modern optimization techniques
  4. You prepare your application for future innovations in the Next.js ecosystem

In the next chapter, we'll look at development environment configuration and practices that will help you work as efficiently as possible with Next.js 16 - like a Quantum Metropolis engineer controlling the city's vast systems from a single terminal.

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Turbopack is the default bundler in Next.js 16. Which flag do you add to the next dev command to use Webpack instead?

  2. 2. Which function from next/dynamic do you use to lazy-load a heavy component?

  3. 3. Which import style is best for bundle size?

Hands-on tasks in the game

  • Click in order

    Arrange the command that launches the development server with Webpack instead of the default Turbopack

  1. QuestionFlag That Switches Back to Webpack
  2. Click in orderLaunching with Webpack
  3. QuestionLazy Loading a Component
  4. QuestionOptimizing Imports

Useful articles