Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
Why is tree shaking not removing unused code when using ES6 modules in my JavaScript project?
Asked on Jan 07, 2026
Answer
Tree shaking is a technique used to eliminate dead code in JavaScript projects, especially when using ES6 modules. If it's not working, there could be several reasons. Here's a basic example and some considerations to ensure tree shaking functions correctly.
<!-- BEGIN COPY / PASTE -->
// utils.js
export function usedFunction() {
console.log("This function is used.");
}
export function unusedFunction() {
console.log("This function is not used.");
}
// main.js
import { usedFunction } from './utils.js';
usedFunction();
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- Ensure your build tool (like Webpack, Rollup, or Parcel) is properly configured to support tree shaking.
- Use ES6 "import" and "export" syntax, as tree shaking relies on static analysis of these statements.
- Check that your build is in "production" mode, as tree shaking is often disabled in "development" mode.
- Verify that your modules don't have side effects, as this can prevent tree shaking from removing unused code.
Recommended Links:
