Tree Shaking: Bundle Only the Code You Use
🎯 Introduction
By the end of this article, you will understand tree shaking, why it relies on ES modules, and how to write code that supports it to keep your libraries small.
🧱 What Is Tree Shaking?
Tree shaking automatically removes unused code during bundling.
Imagine shaking a fruit tree: ripe fruit (unused code) falls away, leaving only the parts you need.
Recall the example from the first article:
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
import { add } from './math.js';
console.log(add(1, 2));
The bundle contains add but not subtract. Since the entry point only references add, Rollup determines that subtract is unused and removes it.
Rollup pioneered and popularized tree shaking, which is now a standard feature of modern bundlers.
✨ Why Does Tree Shaking Rely on ES Modules?
The key requirement is being able to determine which code is used through static analysis, without executing it.
ES modules make this possible:
// import / export declarations are static and appear at the top level
import { add } from './math.js';
export { add };
CommonJS exports, by contrast, are dynamic and can appear inside conditional logic:
// With CommonJS, determining the exports can require executing the code
if (process.env.NODE_ENV === 'production') {
module.exports = { add };
} else {
module.exports = { add, subtract };
}
Remember: ES modules (import / export) provide the foundation for tree shaking. This is why your published library should include an es build.
🛠 Trying Tree Shaking
Let's see a more concrete example. Install lodash-es version 4.17.21:
npm install lodash-es@4.17.21
Use just one function:
import { debounce } from 'lodash-es';
export { debounce };
Bundle it with the node-resolve plugin:
import resolve from '@rollup/plugin-node-resolve';
export default {
input: 'src/index.js',
output: {
file: 'dist/bundle.js',
format: 'es'
},
plugins: [resolve()]
};
The full lodash-es source contains thousands of functions, yet the resulting bundle.js has only a few hundred lines. Rollup includes only debounce and its internal dependencies, removing the other functions.
lodash-es over lodash. The former uses ES modules and supports tree shaking; the latter uses CommonJS and is bundled as a whole.💡 sideEffects: Identifying Files That Must Be Kept
Some files may appear unused when looking only at imports and exports, yet have important side effects. For example:
// Export nothing; patch a global prototype instead
Array.prototype.myCustomMethod = function () {
// ...
};
Such files could be mistaken for unused code and removed. To help prevent this, declare sideEffects in your library's package.json:
{
"name": "my-utils",
"sideEffects": false
}
"sideEffects": falsedeclares that all files are free of side effects and can safely be removed when unused.- If specific files have side effects, list them in an array:
"sideEffects": ["src/polyfill.js"].
This field gives the consumer's bundler a hint that enables more thorough optimization of your library.
❓ Questions and Answers
Q1: Do I need to enable tree shaking explicitly?
No. Rollup enables it by default without additional configuration.
Q2: If I import a module but use only one function, can the others be removed?
It depends on how you import it. A named import such as import { debounce } from 'lodash-es' allows unused parts to be removed precisely. Importing the CommonJS package with import _ from 'lodash' does not.
Q3: Can a library written in TypeScript support tree shaking?
Yes, as long as the published JavaScript uses ES modules. Set the compiler's module option to ESNext rather than compiling to CommonJS.
Q4: Do Webpack and Vite support tree shaking too?
Yes. After Rollup popularized it, Webpack and Vite (whose production builds use Rollup) also adopted tree shaking. ES modules remain the prerequisite.
🧪 Exercise
Verify the effect of tree shaking:
- Install
lodash-es@4.17.21inrollup-demo. - Build the following two versions and compare their bundle sizes:
- Version one:
import { debounce } from 'lodash-es' - Version two:
import { debounce, throttle, cloneDeep } from 'lodash-es', exporting all three
- Version one:
- Check whether the second bundle is larger than the first.
// Add your imports here, then run npm run build to compare the output
🎉 You now understand how tree shaking works! Next, we will combine everything covered so far to bundle and publish a complete utility library.
