Tree Shaking

إزالة الكود الميت (Tree Shaking)

Intermediateperformance1 min read
dead code eliminationbundle tree shakingwebpack tree shakeunused code removal

Definition

A build optimization that removes unused JavaScript code from the final bundle to reduce its size.

تحسين بناء يُزيل كود JavaScript غير المستخدم من الحزمة النهائية لتقليل حجمها.

Why It Matters

Lucide React icons in 404Fault are tree-shaken — only the icons you actually import (BookOpen, Loader2, etc.) end up in the bundle. Importing from barrel files can break tree shaking.

أيقونات Lucide React في 404Fault تخضع لـtree shaking — فقط الأيقونات التي تستوردها فعليًا (BookOpen، Loader2، إلخ) تنتهي في الحزمة. الاستيراد من ملفات barrel يمكن أن يكسر tree shaking.

Full Definition

Tree shaking is a dead code elimination technique used by bundlers (Webpack, Rollup, esbuild). If you import only `{ useState }` from React, tree shaking removes all the other React exports from the bundle. Works best with ES Modules. Next.js uses tree shaking automatically. Lucide-React, the icon library in 404Fault, is tree-shakeable — only imported icons are included in the bundle.
Tree shaking تقنية إزالة الكود الميت تستخدمها الحزمات (Webpack، Rollup، esbuild). إذا استوردت `{ useState }` فقط من React، تُزيل tree shaking جميع تصديرات React الأخرى من الحزمة. Next.js يستخدم tree shaking تلقائيًا.

Example Usage

// Good (tree-shakeable): import { BookOpen, Loader2 } from 'lucide-react'; // Bad for bundle size: import * as Icons from 'lucide-react'; // includes ALL icons

// جيد (قابل لـtree shaking): import { BookOpen, Loader2 } from 'lucide-react'; // سيء لحجم الحزمة: import * as Icons from 'lucide-react'; // يتضمن جميع الأيقونات

Knowledge Graph

Avoid these mistakes when using Tree Shaking:

1

Importing entire libraries when only one function is needed: `import _ from 'lodash'` vs `import debounce from 'lodash/debounce'`

2

Using CommonJS require() — prevents tree shaking which requires ES Modules

Sign in to unlock guided AI explanations from AI Teacher.

Generate a Prompt

Copy this prompt and use it directly with any AI model — no setup needed.

Ready-to-Use Prompt
Help me build a project using Tree Shaking.

Explain:
1. What is Tree Shaking and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Importing entire libraries when only one function is needed: `import _ from 'lodash'` vs `import debounce from 'lodash/debounce'`, Using CommonJS require() — prevents tree shaking which requires ES Modules
5. Best practices and production tips

Official Resources