Ask any question about JavaScript here... and get an instant response.
Why isn't tree shaking removing unused code from my ES6 module bundle in Webpack?
Asked on Nov 17, 2025
Answer
Tree shaking is a technique used to eliminate dead code in JavaScript modules. If it's not working in your Webpack setup, it might be due to improper configuration or usage of non-ES6 module syntax. Here's a basic example of how to ensure tree shaking works in Webpack.
// src/math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// src/index.js
import { add } from './math';
console.log(add(2, 3));
// webpack.config.js
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: __dirname + '/dist',
},
optimization: {
usedExports: true,
},
};Additional Comment:
✅ Answered with JavaScript best practices.- Ensure that you are using ES6 module syntax (import/export) as tree shaking relies on static analysis of these.
- The "mode" in Webpack should be set to "production" to enable optimizations like tree shaking.
- The "optimization.usedExports" option should be enabled to mark unused exports, which is necessary for tree shaking.
- Verify that the modules you are importing are also written in ES6 syntax and are not using CommonJS (require/module.exports).
Recommended Links:
