Side Effects and 'sideEffects' Field
What you'll learn: How the sideEffects field in package.json tells bundlers which files can be safely removed during tree shaking.
Understanding Side Effects
In bundling terms, a side effect is code that does something beyond just exporting values—it modifies global state, patches prototypes, imports CSS, or runs code immediately when imported.
// Has side effects - modifies global scope
window.myLibrary = { version: '1.0' };
// Has side effects - polyfill
Array.prototype.customMethod = function() { /* ... */ };
// No side effects - pure export
export function calculate(x, y) { return x + y; }
The Problem for Tree Shaking
Bundlers are conservative. If they don't know whether importing a module causes side effects, they must include it even if you don't use its exports—just in case. This defeats tree shaking.
The sideEffects Field Solution
The sideEffects field in package.json explicitly declares which files have side effects:
{
"name": "my-library",
"sideEffects": false
}
false means "no files have side effects—tree shake everything."
{
"sideEffects": ["./src/polyfills.js", "*.css"]
}
Array of paths means "only these files have side effects; everything else is safe to tree shake."
How Bundlers Use This Information
When you import from a package marked "sideEffects": false, the bundler knows it can safely drop unused exports. Without this field, bundlers must assume every file might have side effects and include them all.
Key Takeaway: The sideEffects field tells bundlers which files modify global state or run initialization code, enabling aggressive tree shaking for everything else—turning properly configured libraries from bloated bundles into lean, optimized imports.