Skip to content
jshacks.dev
Tooling

Why tree shaking fails on side effects

Tree shaking keeps an import when its module might have side effects, so mark pure packages with sideEffects false in package.json to let bundlers drop them.

1 min read
Summarize in AI

A bundler removes unused exports only when it can prove that removing the module changes nothing. If a module might do something at load time, it stays.

src/analytics.jsJavaScript
window.dataLayer = window.dataLayer || [];
export function track(name) { window.dataLayer.push({ name }); }
export function unused() { return 1; }
src/main.jsJavaScript
import { track } from './analytics.js';
track('open');

Here unused is dropped, because the bundler can see nothing uses it. But the assignment on the first line runs at import time, so the module cannot be skipped. For code the bundler cannot judge, the sideEffects field in package.json is the escape hatch.

package.jsonJSON
{
  "name": "acme-utils",
  "sideEffects": false
}

false promises that importing any file in the package does nothing except define exports, so an unused import can be removed whole. A package with CSS imports or polyfills must list those files instead, such as "sideEffects": ["*.css"], or they will be dropped. See webpack's tree shaking guide.

Re-exporting everything from a barrel file and CommonJS output are the other usual causes of a bundle that stays large.

Taggedbundlers
Share

More snippets

Tooling

Create a Vite project from a template

Create a Vite project from a template with npm create vite, choose the vanilla-ts or react-ts template and see which files it generates.

1 min read
Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
Tooling

Configure VS Code settings for a team

Share VS Code settings and recommended extensions with a team by committing a .vscode folder with settings.json and extensions.json.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.