What is tree shaking and how to enable it
· Category: JavaScript
Short answer
Tree shaking is a dead code elimination technique that analyzes static import/export statements to remove unused exports from the final bundle.
How it works
Bundlers mark exports as used or unused based on import analysis. During optimization, unused code is removed if the module has no side effects.
Steps
- Use ES Modules:
javascript // utils.js export function used() { } export function unused() { } - Import only what you need:
javascript import { used } from "./utils.js"; - Mark your package as side-effect free:
json { "sideEffects": false } - Configure the bundler to optimize:
javascript // webpack optimization: { usedExports: true }
Tips
- Avoid side effects at the module level to help the bundler remove unused code.
- Named exports shake better than default exports in some tools.
Common issues
- Pollyfills and global styles often break tree shaking because they have side effects.
- CommonJS modules are harder to tree-shake due to dynamic evaluation.