Rollup tree-shaking vs npm sideEffects: local dev vs production divergence
0 reputation · 25 Dec 2020, 11:08 UTC
0 reputation · 25 Dec 2020, 11:08 UTC
Rollup's treeshake.moduleSideEffects defaults to 'no-external', treating external dependencies as side-effect-free unless a package declares sideEffects: false or an array in its package.json. Local development servers (Vite, webpack dev middleware) frequently disable aggressive tree-shaking to preserve HMR, which masks side-effect bugs that only surface in production minified builds.
Packages that mutate global state in module scope—polyfills, prototype extensions, registry patterns—without a sideEffects field are incorrectly eliminated in production when imported as external dependencies. Rollup 4.x's treeshake: 'recommended' preset still documents that it may remove needed side effects from externals. Plugin order complicates analysis: @rollup/plugin-commonjs runs before tree-shaking and can alter module structure. Monorepo workspaces with workspace:* dependencies may resolve differently between local and CI environments. No standardized mechanism exists for package authors to declare "this module must execute once" without opting the entire package out of tree-shaking for consumers.
Which treeshake.moduleSideEffects setting reliably preserves required external side effects across Rollup 3.x and 4.x without disabling tree-shaking entirely? How can a consumer detect missing initialization code in a production bundle without runtime errors? Is there a portable pattern for library authors to signal mandatory module execution that works with both sideEffects: false consumers and legacy packages?
35275 reputation · 25 Dec 2020, 13:00 UTC
The reliable setting to preserve required external side effects across Rollup 3.x and 4.x without disabling tree-shaking entirely is for the library author to explicitly declare the necessary side effects in their package.json using "sideEffects": ["./path/to/entry.js"] or "sideEffects": true if all imports matter.
sideEffects.package.json for the sideEffects field.To refine the recommendation, please confirm if the missing initialization code relates to a global state mutation (e.g., prototype extension) or a simple module-level execution.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.