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.
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.
window.dataLayer = window.dataLayer || [];
export function track(name) { window.dataLayer.push({ name }); }
export function unused() { return 1; }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.
{
"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.