Reader Questions About Tree-Shaking and sideEffects
Tree-shaking lets a bundler drop the parts of your package an application never uses. Whether it works well for your users depends partly on how you publish. The questions below come up repeatedly from library authors, grouped from basics to edge cases.
Basics
What is tree-shaking, in one sentence?
It is dead-code elimination based on static import and export statements: if nothing imports a given export, the bundler can leave it out of the final bundle.
Why does the module format matter?
ES module imports and exports are static, so bundlers can analyse them without running code. CommonJS require() calls and dynamic assignments to module.exports are much harder to analyse, so they are usually kept whole. Shipping an ESM build is the first step to being tree-shakeable.
What does the sideEffects field do?
It is a hint to bundlers such as webpack and others that honour it. Setting "sideEffects": false in package.json tells the bundler that importing a module from your package does nothing beyond defining exports, so whole files whose exports are unused can be skipped without evaluating them.
Getting it right
When is false unsafe?
When any file does work at import time: registering a global, patching a prototype, injecting styles, or setting up a polyfill. If the bundler skips such a file, that work silently never happens.
What if only a few files have side effects?
List them instead of using false:
{
"sideEffects": [
"./dist/polyfills.js",
"*.css"
]
}
Everything not matched is treated as side-effect free.
Why do my CSS imports disappear?
A file like import './styles.css' has no exports, so with "sideEffects": false the bundler considers it removable. Include CSS globs in the array, as shown above.
Do barrel files hurt tree-shaking?
An index.js that re-exports everything is fine when the package is correctly marked side-effect free, because the bundler can skip unused modules behind it. Without the flag, the bundler may need to evaluate every re-exported file, and bundles can grow noticeably. Offering subpath exports for large, independent areas also helps.
Checking the result
How do I know whether my package tree-shakes?
Create a tiny test application that imports one small export, build it in production mode with a mainstream bundler, and inspect the output. Bundle analyser plugins or a simple search of the output for a function you did not import will tell you quickly. Repeat with a second bundler if your users are split between tools.
Should I publish bundle-size numbers?
Only if you measure them reproducibly and say how: which bundler, which version, which import. Numbers without a method invite arguments, and they go stale with every release.
Is changing sideEffects a breaking change?
It can be. Marking a package side-effect free when it was not can drop behaviour some users relied on. Treat the change with care, test it with real applications, and mention it in the changelog.