Carlos Cifuentes
Glossary

Tree shaking

Tree shaking is the build step in which a bundler removes code that is exported but never imported, so that it does not reach the production bundle.

A bundler starts from the entry point of the application and follows every import. Anything that is never reached can be left out. This works because ES module imports and exports are static: the bundler can see which names are used without running the code. The term comes from the image of shaking a tree so that the dead leaves fall off.

Example

A utility file exports two functions:

export function formatDate(d: Date) { /* ... */ }
export function formatCurrency(n: number) { /* ... */ }

The application imports only formatDate. In the production build, formatCurrency is dropped. The same applies to libraries. Importing one function from a date library includes only that code, provided the library ships ES modules.

Common misunderstanding

Tree shaking is often trusted to remove everything unused. It is conservative. If a module might have side effects when it loads, such as registering something globally, the bundler keeps it. Libraries declare that they are safe through the sideEffects field in package.json. Libraries published only as CommonJS are hard to analyze and tend to be included whole.

The way code is written matters too. AngularJS registers controllers and services by string name on a global module, so a bundler cannot tell which ones are used, and the whole application ships. Modern Angular is designed for the opposite. Standalone components import what they use, and services declared with providedIn: 'root' are dropped when nothing injects them.

Federation adds one exception. A library shared between a host and its remotes is usually loaded whole, because the build cannot know what each remote will need. Share only what must exist as a single instance. More in micro-frontends.

Why it matters. AngularJS code cannot be tree-shaken in any useful way, so bundle size drops as screens move to modern Angular. In a federated platform, the list of shared libraries limits what tree shaking can remove.

Related terms

Planning a migration or a micro-frontend platform?

In a 20-minute call you describe your situation and I tell you how I'd approach it. If it isn't worth doing yet, I'll say so.

Message me on LinkedIn