Key Takeaways
- Tree shaking removes unused code from bundles, often reducing JavaScript size by 30-60% for large libraries.
- It only works with ES module syntax (import/export). CommonJS (require) cannot be tree-shaken.
- Import specific functions (`import { map } from 'lodash-es'`) instead of entire libraries to enable effective tree shaking.
Maximizing Tree Shaking Effectiveness
- Use ES module versions: Import from 'lodash-es' instead of 'lodash'. Check if libraries offer ESM builds.
- Import specifically: `import { Button } from '@/components/ui/button'` instead of `import * as UI from '@/components/ui'`.
- Mark side-effect-free: Add `"sideEffects": false` to package.json so bundlers can safely remove unused exports.
- Analyze bundles: Use `npx vite-bundle-visualizer` or `webpack-bundle-analyzer` to identify large, poorly tree-shaken dependencies.
- Avoid barrel files: Re-exporting everything from index.ts files can defeat tree shaking in some bundler configurations.
Frequently Asked Questions
Related Services
Need Help With Implementation?
Our team specializes in implementing the solutions described in this glossary.
Get in Touch