Reduce Your Bundle Size with Effective Tree Shaking
Modern JavaScript bundlers are smart—but they’re not mind readers. If you want smaller production bundles, you need to structure your code in a way that makes unused code easy to remove.
What actually makes tree shaking work?
Tree shaking relies on static analysis. That means your code has to be predictable and explicit so the bundler can safely eliminate what’s not used.
Here are the fundamentals:
1. Stick to ES Modules
Use import / export syntax so the bundler can analyze dependencies at build time.
import { fetchData } from " ./api " ;
export const load = () => fetchData ();
Enter fullscreen mode
Exit fullscreen mode
Avoid CommonJS where possible:
const { fetchData } = require ( " ./api " );
Enter fullscreen mode
Exit fullscreen mode
This pattern makes it harder for bundlers to optimize.
Be precise with imports
Pulling in an entire library when you only need one function is one of the fastest ways to bloat your bundle.
// ❌ Pulls in…