0
0
AngularHow-ToBeginner Ā· 3 min read

How to Use Tree Shaking in Angular for Smaller Bundles

In Angular, tree shaking is enabled by default when you build your app with ng build --prod. It works by removing unused code from your final bundle, making your app smaller and faster without extra configuration.
šŸ“

Syntax

Tree shaking in Angular happens during the production build process using the Angular CLI. The main command to trigger it is:

  • ng build --prod: Builds the app with optimizations including tree shaking.

This command uses webpack and terser under the hood to analyze and remove unused code.

bash
ng build --prod
šŸ’»

Example

This example shows how to build an Angular app with tree shaking enabled by default. Unused components or services will be removed from the final bundle.

bash
/* Assume you have an Angular app with some unused service or component */

// Run this command in your project root:
ng build --prod

// The output will be in the 'dist/' folder with a smaller bundle size due to tree shaking.
Output
āœ” Browser application bundle generation complete. āœ” Initial chunk files optimized. Your application has been built successfully. The output is in the 'dist/' folder with minimized and tree-shaken bundles.
āš ļø

Common Pitfalls

Common mistakes that prevent tree shaking from working well in Angular include:

  • Importing entire libraries instead of specific modules or functions, which keeps unused code.
  • Using dynamic code patterns like require() or eval() that confuse the bundler.
  • Not building with --prod or enabling optimization flags.

Always import only what you need and use the Angular CLI production build for best results.

typescript
/* Wrong way: importing entire lodash library */
import * as _ from 'lodash';

/* Right way: import only needed functions */
import { debounce } from 'lodash-es';
šŸ“Š

Quick Reference

  • Enable tree shaking: Use ng build --prod or ng build --configuration production.
  • Use ES modules: Import specific functions or modules, not whole libraries.
  • Avoid dynamic imports: Static imports help bundlers analyze code better.
  • Check bundle size: Use tools like source-map-explorer to verify tree shaking effectiveness.
āœ…

Key Takeaways

Tree shaking is enabled by default in Angular production builds using ng build --prod.
Import only the parts of libraries you need to help tree shaking remove unused code.
Avoid dynamic or complex import patterns that prevent static analysis.
Use Angular CLI production configuration for optimized, smaller bundles.
Check your final bundle size with tools to confirm tree shaking effectiveness.