Next.jsMedium

What is tree shaking and does Next.js support it?

Tree shaking removes unused exports from the final bundle by analyzing ES module import/export statements. Next.js supports it in production builds with both Turbopack (default) and webpack, and adds optimizePackageImports to handle large "barrel" packages that defeat normal tree shaking.

Requirements for it to work

  • ES modules: CommonJS (require, module.exports) is hard to analyze and usually is not shaken.
  • Side-effect information: packages declare "sideEffects": false in package.json so unused modules can be dropped entirely.
  • Named imports: import { debounce } from "lodash-es" instead of the whole library.

Barrel files

Packages that re-export everything from an index.js (icon sets, UI kits) force the bundler to parse thousands of modules, slowing builds and sometimes keeping unused code. optimizePackageImports rewrites imports to the exact modules. Next.js enables it automatically for popular packages such as lucide-react, date-fns, lodash-es, @mui/material and react-icons; add your own in next.config.ts.

What else reduces bundles

  • Server Components keep their dependencies off the client entirely.
  • serverExternalPackages keeps big server-only packages out of the server bundle too.
  • Next.js 16.4 adds export-name mangling in production, which shrinks the JavaScript that does ship.

Verify

Run next analyze (or next build --analyze) to see which modules ended up in each chunk, or @next/bundle-analyzer with webpack builds.

Pitfalls

import * as utils and dynamic property access (utils[name]) prevent shaking. Side effects at module top level (polyfills, CSS imports) keep modules alive.

Code example

tsx
1// next.config.ts
2import type { NextConfig } from "next";
3
4const nextConfig: NextConfig = {
5 experimental: {
6 // Add internal or less common barrel packages (popular ones are automatic)
7 optimizePackageImports: ["@acme/icons", "@acme/ui"],
8 },
9};
10export default nextConfig;
11
12// Good: only the used functions are bundled
13import { format, addDays } from "date-fns";
14import { Search } from "lucide-react";
15
16// Bad: the whole CommonJS library is included
17// import _ from "lodash";
18// _.debounce(fn, 300);
19
20// Better
21import debounce from "lodash-es/debounce";
22
23export const tomorrow = format(addDays(new Date(), 1), "yyyy-MM-dd");
24export const SearchIcon = Search;
25export const onType = debounce((q: string) => console.log(q), 300);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app