Tree shaking in the context of Webpack is a technique for eliminating unused code from the final bundle, reducing its size. Tree shaking is made possible by the static analysis of imports and exports in the code.
How tree shaking works:
- ES6 modules: Tree shaking works best with ES6 modules (import/export) due to their static structure.
- Static analysis: Webpack analyzes the source code and identifies unused exports that can be removed.
- UglifyJS/Terser: Used for minification and further removal of unused code.
Webpack configuration for tree shaking:
- Set the production mode:
module.exports = { mode: 'production', // other settings };
- Use ES6 modules:
// Instead of `require` import { myFunction } from './myModule';
Example Webpack configuration with TerserPlugin:
const TerserPlugin = require('terser-webpack-plugin'); module.exports = { mode: 'production', optimization: { minimize: true, minimizer: [new TerserPlugin()] } };
Tree shaking is a crucial element of bundle size optimization, enabling the delivery of faster and more efficient applications.