Tree shaking is dead-code elimination, but real bundler results depend on ESM, side-effect declarations, and import shape. The production pitfall is assuming unused code disappears automatically when package structure still blocks elimination.
Use this JavaScript interview question to rehearse a quick answer, common mistake, follow-up, and production pitfall.
Tree-Shaking: How It Works and Common PitfallsFrontend interview answer
This JavaScript interview question tests whether you can explain Tree shaking in bundlers: ESM requirements, side-effect pitfalls, and bundle debug, connect it to production trade-offs, and handle common follow-up questions.
- Tree shaking in bundlers: ESM requirements, side-effect pitfalls, and bundle debug explanation without falling back to memorized docs wording
- Modules and Build reasoning, edge cases, and production failure modes
- How you would answer the most likely JavaScript interview follow-up
Bundler pitfall
Tree-shaking is not a magic "remove everything unused" switch. Bundlers need static ESM structure and trustworthy side-effect signals. When bundles stay fat, the debug question is usually where hidden side effects, barrel exports, or import shape prevented elimination.
Requirement | Why it matters | Example |
|---|---|---|
ESM exports | Static analysis of imports | export const foo = ... |
No side effects | Unused code can be safely removed | set "sideEffects": false |
Pure annotations | Signals safe removal | /* @__PURE__ */ helper() |
// Good: named ESM exports
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
// Consumer uses only add
import { add } from './math.js';
Pitfall | Why it breaks tree-shaking | Fix |
|---|---|---|
CommonJS modules | Require is dynamic | Publish ESM build |
Side-effect imports | Bundler must keep them | Mark sideEffects accurately |
Barrel files with side effects | Re-export triggers file execution | Keep barrels side-effect free |
Dynamic require/import | Unknown at build time | Prefer static imports |
How to verify
Use a bundle analyzer to compare sizes before/after. In devtools, inspect the output bundle to ensure unused exports are removed. Add perf budgets to prevent regressions.
Tree-shaking is effective when your code is ESM, side-effect free, and statically analyzable. If bundles stay large, check for CJS dependencies and unmarked side effects.
Use this as one explanation rep, then continue with the JavaScript interview questions cluster or a guided prep path.