What is tree shaking and why is it important and useful?
The idea behind tree shaking is to imagine the various dependencies of code as a tree. On the one hand, this tree becomes bigger, more complex, and more branched over time, because more and more dependencies are added in the form of additional packages. On the other hand, older dependencies are gradually no longer integrated or used. The packages are still there but no longer “tied.”
When you “shake” this tree, everything that is not firmly attached to the trunk or branches falls to the ground – the packages that are no longer firmly tied and therefore no longer needed fall off.
Why does this matter? 170 KB !== 170 KB
In both cases, the browser needs the same amount of time for downloading, because it is the same amount of data.
How should I write my code?
The mechanism behind tree shaking relies on static code analysis enabled by EMS notation (<span class="hljs-keyword">import</span>/<span class="hljs-keyword">export</span>):
webpack marks these code locations on this basis so that they can be removed by tools like UglifyJS.
However, it is necessary that the source, in this case “bar.js,” is written in EMS format. In CommonJS notation, it is not possible for applications such as webpack or Rollup to perform a static code analysis on the basis of this format. Usually you don’t have any problems with files you yourself have created if in them, you use the EMS format.
Caution with dependencies
The <span class="hljs-keyword">import</span> statement does not allow you to recognize whether the source is written in EMS format. This requires that you take a look at the package.json file of the dependency.
As you know, the dependency is resolved with the file that is below the “main” field, but bundlers like webpack or Rollup are looking for the “module” field to find an EMS version of the dependency.
Common dependencies in which the code is not in EMS format include: