Start building

Optimizing JavaScript libraries by making tree shaking actually work

Oliwia Połeć in Developer Console on Apr 26, 2021

The so-called tree shaking is a concept library authors will utilize the most, but the knowledge of the process will also benefit every developer’s daily work. What exactly is tree shaking, and how can you make the most out of it in your projects?

Tree shaking LiveChat

Tree shaking is a process often called a dead code elimination. Usually, it's treated as a synonym for including only live code into the project rather than eliminating the code that resulted as unused in the program. But are these two terms referring to the same actions? This question, and many more, are answered in the article dedicated to the tree shaking topic by one of the LiveChat frontend developers, Mateusz Burzyński. Read more below to see what else we will cover.

It is always a good choice to send the least amount of code to the client’s browser to process. Including particular modules in a project can result in many dependencies added to it, while your code can utilize only a couple of them. Thanks to tree shaking, you can avoid excessive bytes in your project and keep only the dependencies you actually resource at the time. Yet it isn't always a silver bullet, and there are certain actions that can be done to achieve better results. Mateusz dives into this topic and explains it based on easy-to-understand examples.

Tree shaking, as an optimization, is currently performed by the most popular bundlers. The concept is to analyze your program’s logic and see which parts of the code are used, "live" in terms of tree shaking. The code elimination mechanisms are an invaluable help in the process, yet they might result in an imperfect outcome. In the article, you will learn how these tools perform the code analysis and what makes it difficult in JavaScript.

So what those tools have to do is to figure out how your program behaves without actually executing it. They can drop certain code fragments from the tree if they can prove that this won't affect the overall logic of the program.

Mateusz also speaks about the topic of possible side effects of the functions in a project and explains what to consider when constructing your program to result in most effective tree shaking.

You can find the whole article published on Make sure to follow us there if you are into programming-related topics!

Read the article

💡 New to libraries? See how to build a JavaScript library like a pro >>

Latest articles

Jun 6, 2024

What Is GitHub Used For and How Can It Enhance Your Projects...

Jun 4, 2024

Discover the Best Code Editor: Top Choices for Developers in...

May 23, 2024

The Developer's Blueprint: How to Become a Software Develope...