Summary: Tree Shaking Checklist
Now I can summarize.
For tree shaking to work:
- Use ES Modules:
import/export, not CommonJS - Prefer named imports:
import { fn }>import lib - Declare sideEffects: Specify in package.json
- Watch barrel files: Only when needed, only lightweight
- Static imports: Minimize dynamic imports
- Production build: Dev mode doesn't tree shake
- Verify: Check with bundle analyzer
When building libraries:
- Provide ES Modules version (
modulefield) - Design around named exports
- Declare
sideEffects: false - Specify entry points with
exportsfield
Common mistakes:
- Using lodash instead of lodash-es
- Bringing everything with default import
- Re-exporting heavy modules in barrel files
- Not specifying sideEffects in package.json
- Wondering "why doesn't it work?" in development mode
Tree shaking isn't magic. Write code that build tools can statically analyze, and they'll automatically drop dead code. To properly shake a tree, you need to plant it in a way that allows shaking. That was the key insight.