Tree Shaking In Javascript

jscleancodees6

Tuesday, November 14, 2023

Tree shaking is a term commonly used in the JavaScript context for dead-code elimination. It relies on the static structure of ES2015 module syntax, i.e., import and export. The concept has been popularized by the ES2015 module bundler rollup .

What is Tree Shaking?

Tree shaking means removing unreachable code (also known as dead code) from a bundle. You can imagine your application as a tree. The source code and libraries you actually use represent the green, living leaves of the tree. Dead code represents the brown, dead leaves of the tree that are consumed by autumn. In order to get rid of the dead leaves, you have to shake the tree, causing them to fall .

Why Use Tree Shaking?

Tree shaking helps reduce the weight of the application. For instance, if you just want to create a “Hello World” Application in AngularJs 2, it will take around 2.5MB, but by tree shaking, we can bring down the size to just a few hundred KBs, or maybe a few MBs.

Implementing Tree Shaking

Tree shaking is implemented using tools like webpack. These tools detect dead code and mark it as “unused module” but it won’t remove the code. Webpack relies on minifiers to clean up dead code, one of them is UglifyJS plugin, which will eliminate the dead code from the bundle .

Here's an example:

// modules.js
export function drive(props) {
 return props.gas
}

export function fly(props) {
 return props.miles 
}

// main.js
import { drive } from modules;

/// some code
eventHandler = (event) => {
 event.preventDefault()
 drive({ gas: event.target.value })
}
/// some code

// fly() was never imported and won't be included in our bundle

In this example, fly() was never imported and won't be included in the bundle, thus reducing the size of the bundle.

However, tree shaking only works with import and export. It won’t work with CommonJS require syntax .

Best Practices for Tree Shaking

To take advantage of tree shaking, you must:

  • Use ES2015 module syntax (i.e., import and export).
  • Ensure no compilers transform your ES2015 module syntax into CommonJS modules (this is the default behavior of the popular Babel preset @babel/preset-env).
  • Add a "sideEffects" property to your project's package.json file.
  • Use the production mode configuration option to enable various optimizations including minification and tree shaking (side effects optimization is enabled in development mode using the flag value).
  • Make sure you set a correct value for devtool as some of them can't be used in production mode.