Tree Shaking vs Minification: What Each One Does

Tree Shaking vs Minification: What Each One Does

Minification shortens the JS you keep. Tree shaking drops unused modules. See the difference, Vite/Webpack setup, and when to use both.

13.05.2026
9 min read
Share this article:
JavaScriptTree shakingMinificationWebpackVitePerformanceOptimizationBundleTutorial

Two techniques people mix up

Optimizing a modern frontend means hearing “minify your bundles” and “tree-shake your bundles” all the time. They are not synonyms. Minification shrinks code that is already in the final file (whitespace, shorter identifiers). Tree shaking removes modules that are never used from the dependency graph. Both cut the bytes transferred, at different stages of the pipeline. For a single file without a bundler, an online JavaScript minifier is often enough. A full application usually combines static import analysis, a production bundler and a minifier (Terser, esbuild, SWC or Oxc). This guide gives the definitions, a comparison table, measured sizes and a Vite and Webpack setup. For deeper tuning, see our JavaScript minification guide.

Know which lever cuts the number of modules and which one cuts the bytes of the files you keep
Stop assuming minification removes all of lodash when you only need one helper
Wire the bundler and the minifier so tree shaking and minification add up
Spot when CSS needs purging (Tailwind, PurgeCSS) before it is minified
Measure with a bundle analyzer instead of guessing the savings

Minification and tree shaking do different jobs

Minification shrinks what stays in the file

Minification works on a file whose contents are already decided. It removes whatever the JavaScript engine does not need (whitespace, comments and, depending on the tool, local variable names). It cannot tell whether an exported function will matter later if it is already in the bundle. For the fundamentals and a comparison of tools, see our complete JavaScript minification guide. When you need readable code again, keep an online JavaScript unminifier or the Beautify mode at hand.

Before

function calculateTotal(price, quantity) { const taxRate = 0.2; return price * quantity * (1 + taxRate); } export { calculateTotal };

After

function calculateTotal(n,t){return n*t*1.2}export{calculateTotal};
Tree shaking prunes unused branches from the graph

Tree shaking relies on ES modules (`import` / `export`) and static analysis. Anything unreachable from an entry point can be dropped before minification runs. Libraries must ship compatible builds (`sideEffects` in `package.json`, no hidden global side effects). The most telling fix is to replace a barrel or default import with a precise import.

Prefer named imports from lodash-es, or deep paths, over default imports of lodash when your toolchain shakes well
Expose the module and exports fields in the package.json of your libraries so bundlers resolve builds they can analyze statically
Set sideEffects to false (or to a precise list) in your own packages when their files have no side effects
Avoid very broad dynamic imports that keep whole chunks without finer analysis
Use code splitting for code that only some pages need: shaking drops unreachable code, splitting only defers reachable code

Before

// utils/math.ts: unused exports can end up in the bundle export function square(x){return x*x} export function cube(x){return x*x*x} export function unusedLegacy(){/* legacy API */} // main.ts import { square } from './utils/math'

After

// After the bundler's analysis, only the definitions // that are actually referenced can stay in the chunk, // then minification shortens the syntax further. // cube() and unusedLegacy() can be dropped // if no other file imports them.
For CSS, purging plays the part of tree shaking

CSS has no ES-module tree shaking like JavaScript. PostCSS, Tailwind and PurgeCSS do the same job instead: they remove unused rules before you run an online CSS minifier or cssnano on the final output.

Scan your JSX and HTML templates so only the Tailwind classes you really use are shipped
Retire old global stylesheets once styles live next to their components
Check the result visually after a purge: classes built by string concatenation may be removed by mistake
Minify after the purge for a further, smaller saving

Measure what actually moves in your bundle

Compare before and after

The two techniques show up in different parts of a bundle report. Tree shaking cuts the number and size of modules. Minification shrinks the bytes of the modules that remain. In a test with Vite 8.3.4 and only the debounce function of lodash-es, the bundle weighed 85.0 KB minified with tree shaking turned off. It weighed 13.9 KB shaken but not minified, and 2.9 KB with both. Use a treemap to catch regressions after dependency updates.

Diagram comparing a heavy bundle with a reduced bundle after optimization
rollup-plugin-visualizer, webpack-bundle-analyzer or vite-bundle-visualizer
Source Map Explorer to trace bytes back to their source files
Chrome DevTools Coverage to compare the JavaScript and CSS that runs with what is shipped
gzip and Brotli comparisons after the build to see the real transfer savings
Build in production mode

Build in production mode: `vite build` and Webpack's `mode: 'production'` set `NODE_ENV` for you. With other tools, set `NODE_ENV=production` yourself. Without it, some bundlers skip optimizations and libraries such as React keep their development code.

Make sure CI runs the same command as the build that produces your staging artifacts
Set bundle size budgets and check them in the pipeline
Compare builds around major npm upgrades: one dependency can break shaking

The two techniques side by side

At-a-glance comparison

Use this when you size an optimization ticket. First ask whether the code should be in the graph at all. Then ask how to shrink its text.

Minification

goal:Rewrite the remaining code to drop syntax that is not needed
when:After bundling, or on an isolated file
example:13.9 KB down to 2.9 KB on a shaken bundle (test above)
limits:Cannot drop a module that is imported but unused

Tree shaking

goal:Remove exports and modules that no entry point reaches
when:While resolving the ES module graph
example:85.0 KB down to 2.9 KB on a minified bundle (test above)
limits:Fails on opaque dynamic code, or on CommonJS that is not analyzed
A short checklist

These checks keep an optimization from staying on paper.

Do I still import whole packages where a precise path exists?
Do my libraries declare sideEffects honestly, so bundlers can prune?
Does minification run after shaking, to shrink what remains?
Do I need an online tool for a snippet outside the bundle, or a full rebuild of the app?
For CSS, did I purge before judging what minification alone saves?

Minify a standalone file

FastMinify for one-off passes

When Webpack or Vite is not set up yet, or when you ship a single script, paste your JavaScript into our client-side tool. It returns compact code and a Beautify mode to read it again.

1

Paste or load your file

Use the online JavaScript minifier. Your code stays in your browser.

2

Switch to Beautify

Switch to Beautify for a readable layout. This is handy before you copy the code back into your toolchain.

3

Do not confuse it with shaking

The tool minifies the files you give it and does not analyze which modules are used. Dropping unused modules takes a production bundler working on the module graph.

Fit into modern workflows

As your codebase grows, follow the advice in our online minifiers vs build tools guide. The online tool stays useful for exceptions and quick checks.

Prototype or static landing page: online minifier
SPA or SSR app: bundler, tree shaking and minification
One-off audit: unminify with FastMinify, then fix at the source

Combine tree shaking and minification in builds

Vite (Rolldown under the hood since version 8)

`vite build` applies tree shaking and minifies with Oxc by default (Vite 8, built on Rolldown). Vite 7 and earlier used Rollup and esbuild. Keep your imports ES-module friendly.

Configuration

// vite.config.ts (snippet) import { defineConfig } from 'vite' export default defineConfig({ build: { minify: 'oxc', // default in Vite 8; 'terser' stays available sourcemap: true, // keeps stack traces readable in production }, })

Usage

# Production build npm run build # Inspect dist/assets/*.js: the chunks show # what the bundler kept after tree shaking, then minified.
Webpack 5

`mode: 'production'` turns on `usedExports`, `sideEffects` and minification with Terser. Check that the libraries you use declare `sideEffects` accurately.

Configuration

// webpack.config.js (snippet) module.exports = { mode: 'production', optimization: { usedExports: true, sideEffects: true, // honors the "sideEffects" field of package.json minimize: true, // The default minimizer is TerserPlugin. To add another one // and keep Terser, use minimizer: ['...', new MyPlugin()]. }, };

Usage

// Entry wiring: // webpack traces exports from the entry points, // marks unused exports, then the minimizer shrinks the bytes. import { initApp } from './app' initApp()
CSS in production

Chain the Tailwind or PurgeCSS purge, then minification, as in our CSS minification guide. The purge does the shaking, and minification then shrinks the bytes of what is left.

Basic example

/* After unused classes are purged */ .btn{padding:.5rem 1rem;border-radius:.375rem}

File minification

/* postcss + cssnano at the end of the pipeline */ .btn{padding:.5rem 1rem;border-radius:.375rem} /* the output is a single compact line */

Conclusion

Tree shaking and minification complement each other. One trims the dependency graph, the other writes what remains in fewer bytes. Without tree shaking, you ship dead modules. Without minification, you ship verbose output for an already slim graph. An online minifier covers snippets outside your repository. Automate your bundler for everything else. Keep FastMinify at hand for edge cases.

Minify your JavaScript in your browser

Combine precise ES imports, honest sideEffects metadata and production builds
Measure with a bundle analyzer after changing dependencies
For CSS, purge first, then minify, as in our CSS minification guide
Keep the online-versus-build comparison at hand for team decisions
To read compact JavaScript, beautify or unminify it before debugging
Share this article
Share this article: