web-performance-optimization
/

Tree Shaking in Web

Last Sync: Today

On this page

9
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

web-performance-optimization

Tree Shaking in Web

What is Tree Shaking?

Tree shaking is a technique used to remove unused code from JavaScript bundles, reducing file size and improving performance.

Why Tree Shaking Matters

Large JavaScript bundles slow down websites. Tree shaking ensures only the necessary code is included, improving load speed and efficiency.

Basic Example

JavaScriptRead-only
1
// utils.js
export function add(a, b) { return a + b; }
export function multiply(a, b) { return a * b; }

// main.js
import { add } from './utils.js';
console.log(add(2, 3));

How Tree Shaking Works

  • Uses ES Modules (import/export)
  • Removes unused exports
  • Works during build process (Webpack, Rollup)

Requirements for Tree Shaking

  • Use ES6 modules (import/export)
  • Use a bundler like Webpack or Rollup
  • Avoid side effects in modules

Benefits of Tree Shaking

  • Reduced bundle size
  • Faster load times
  • Improved performance
  • Efficient code delivery

Best Practices

  • Use ES module syntax
  • Avoid importing entire libraries
  • Use modular libraries (e.g., lodash-es)
  • Configure bundler properly

Common Mistakes

  • Using CommonJS instead of ES modules
  • Importing full libraries unnecessarily
  • Ignoring side effects in modules
  • Not configuring bundler for production

Conclusion

Tree shaking is a powerful optimization technique that removes unused code and improves web performance by reducing bundle size.

Try it yourself

import { add } from './utils.js';
console.log(add(2, 3));

Test Your Knowledge

Q1
of 3

What does tree shaking remove?

A
Images
B
Unused code
C
CSS
D
HTML
Q2
of 3

Which syntax is required?

A
require
B
import/export
C
fetch
D
eval
Q3
of 3

Which tool supports tree shaking?

A
Photoshop
B
Webpack
C
MySQL
D
Figma

Frequently Asked Questions

What is tree shaking?

Removing unused code from JavaScript bundles.

Does tree shaking work with CommonJS?

No, it works best with ES modules.

Which tools support tree shaking?

Webpack and Rollup.

Previous

web minification

Next

web bundling

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.