Tree shaking

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search

In computing, tree shaking is a dead code elimination technique that is applied when optimizing code written in ECMAScript dialects like Dart, JavaScript, or TypeScript into a single bundle that is loaded by a web browser. Rather than eliminating code that can never be executed, tree shaking starts from entry point and includes only the code that can ever be executed.[1] It is succinctly described as "live code inclusion".

History[edit]

Dead code elimination in dynamic languages is a much harder problem than in static languages. The idea of a "treeshaker" originated in LISP[2] in the 1990s. The idea is that all possible execution flows of a program can be represented as a tree of function calls, so that functions that are never called can be eliminated.

The algorithm was applied to JavaScript in Google Closure Tools and then to Dart in the dart2js compiler also written by Google, presented by Bob Nystrom in 2012[3][4] and described by the book "Dart in Action" by author Chris Buckett in 2013:

When code is converted from Dart to JavaScript the compiler does 'tree shaking'. In JavaScript you have to add an entire library even if you only need it for one function, but thanks to tree shaking the Dart-derived JavaScript only includes the individual functions that you need from a library

— Chris Buckett

The next wave of popularity of the term is attributed to Rich Harris’s Rollup project[5] developed in 2015.

Relation to ECMAScript 6 modules[edit]

The popularity of tree shaking in JavaScript is based on the fact that in distinction from CommonJS modules, ECMAScript 6 module loading is static and thus whole dependency tree can be deduced by statically parsing the syntax tree. Thus tree shaking becomes an easy problem. However tree shaking does only apply to the import/export level; it can also work on a statement level, depending on implementation.[citation needed]

References[edit]