Tree shaking is a form of dead code elimination. The term "tree shaking" comes from the mental model of your application and its dependencies as a tree-like structure. Each node in the tree represents a dependency that provides distinct functionality for your app. In modern apps, these dependencies are brought in via static import statements like so:
// Import all the array utilities!
import arrayUtils from "array-utils";
When your app is young (a sapling, if you will), you may have relatively few dependencies. You're also using most (if not all) the dependencies you add. As your app ages, however, more dependencies can get added. To compound matters, older dependencies fall out of use, but may not get pruned from your codebase. The end result is that an app ends up shipping with a lot of unused JavaScript, especially in its dependencies. Tree shaking addresses this by taking advantage of how we use static import statements to pull in specific parts of ES6 modules:
// Import only some of the utilities!
import { unique, implode, explode } from "array-utils";
The difference between this import example and the previous one is that rather than importing everything from the "array-utils" module (which could be a lot of stuff!), this example imports only specific parts of it. In dev builds, this doesn't really change anything, as the entire module gets imported regardless. In production builds, however, we can configure a module bundler (e.g., webpack or Rollup) to "shake" off exports from ES6 modules that weren't explicitly imported, making those production builds smaller.
original source: https://developers.google.com/web/fundamentals/performance/optimizing-javascript/tree-shaking
No comments:
Post a Comment