41. What is 'tree shaking' in the context of Webpack and how does it work?

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:

  1. ES6 modules: Tree shaking works best with ES6 modules (import/export) due to their static structure.
  2. Static analysis: Webpack analyzes the source code and identifies unused exports that can be removed.
  3. UglifyJS/Terser: Used for minification and further removal of unused code.

Webpack configuration for tree shaking:

  1. Set the production mode:
module.exports = { mode: 'production', // other settings };
  1. 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.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.