liveBook · Manning

Tree-shaking

As explained in The Joy of JavaScript

A bundler optimization that removes unused exports, modules, or code paths from a program during build time.

Tree-shaking is a build-time optimization that traces a program’s dependency tree and removes unused modules, exports, and sometimes code paths from the bundled application. section 6.5.1

ECMAScript Modules make this analysis practical because imports are static: they appear at the top level and cannot depend on variables, functions, or conditionals. Dynamic CommonJS loading is harder to analyze. section 6.5.1

Effective tree-shaking depends on how modules and functions are designed:

  • Map imports and exports to identify unreachable modules and remove them from the packaged file. section 6.5.1
  • Keep modules loosely coupled and internally cohesive so bundlers can analyze their dependencies more reliably. section 6.5.1
  • Mark or recognize pure calls whose unused results have no side effects, allowing those calls to be removed as well. section 6.5.1

Unused exports and pure calls

An unused export such as `foo` can disappear from the bundle. A pure call such as `/*#__PURE__*/checkTampering(...)` can also be removed when its result is unused. section 6.5.1

Figure 6.2 Bundler tools can use the static structure of your application to achieve tree-shaking by identifying any unused modules of code and removing them from the packaged application file.

Trace how a bundler uses the application’s static structure to locate unused modules and remove them from the packaged application. section 6.5.1

How The Joy of JavaScript covers it

How deep it goes
Explains dependency analysis, ESM constraints, module design, and pure-call removal, but defers specific build-tool usage.
Examples
Uses unused exports, bundled dependency trees, and pure validation calls as removal examples.
What it assumes
Assumes familiarity with JavaScript modules and distinguishes static ESM imports from dynamic CommonJS loading.
What you can do after
Evaluate module designs and understand how ESM enables bundlers to remove unreachable code.
How it connects
Connects ECMAScript modules, dead-code elimination, CommonJS, dependency management, and pure functions.

Also explained in

Compare how 2 books explain tree-shaking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Joy of JavaScript. The section links point to the parts of the book it draws on.