What is Tree Shaking?

Remove the Dead Code & Reduce the Bundle Size.

๐ŸŒณ Definition

Tree shaking is a process of eliminating the unused code that helps to reduce the bundle size. When the codebase grows, there is a huge chance that we may have ended up adding some extra code that is in the bundle but not used by the application itself. Such code is also known as Dead Code.

Therefore, Tree shaking helps us to eliminate the Dead Code from our bundle.

๐ŸŒณ Important Concepts

  • Tree shaking is performed when the bundle is created. Whenever we create the final build, first, tree shaking removes all the dead code, and then the actually used code is bundled.
  • In Javascript bundling, Tree shaking is achieved via import & export.
  • The term Tree Shaking was first introduced by Rollup and then, later on, was also adopted by Webpack.
  • Make sure that Tree Shaking is not limited to only JavaScript. It's a technique that is highly used in other domains to reduce the package/bundle sizes.

๐ŸŒณ Example

As an example, we have a file called user-service.js and inside of it, we have some basic crud operations. Right now, we are not focusing on the implementations of the methods.

export const getUsers = () => {};

export const createUser = () => {};

export const updateUser = () => {};

export const getUserById = () => {};

As you can see, we are exporting all the functions from this file as a named export. If you want to understand import/export, please read ES6 Modules In Depth.

Now, we can utilize these methods in our files like:

import { getUsers, createUser } from "./user-service";

In this example, we have imported getUsers and createUser. Now all the other methods are considered as a dead code because they are not being used in our app. Therefore when the bundling will happen, only the getUsers and createUser will be inside the bundle. Rest will be eliminated.

That's it, folks! hope it was a good read for you. Thank you! โœจ

Read More:

๐Ÿ‘‰ Follow me: Github Twitter LinkedIn Youtube