What is Tree-shaking


1. What is Tree-shaking?

Tree-shaking is a technique for optimizing JavaScript code, which can automatically remove unused code when packaging. Specifically, it statically analyzes code to determine which code is used and which code is not. It can then remove unused code from the bundled code to reduce file size and optimize performance.

Tree-shaking is an optimization technique based on the ES6 module system. This is because the static nature of the ES6 module system enables code dependencies to be determined at compile time. Therefore, Tree-shaking can perform static analysis at compile time and remove unused code. This process is usually done automatically by packaging tools (such as Webpack, Rollup, etc.).

Using tree-shaking can help developers reduce file size, increase page loading speed, and optimize performance, especially when building large JavaScript applications.

2. How to enable Tree-shaking in Webpack?

To enable Tree-shaking in Webpack, the following steps are required:

Make sure your code is written using ES6 modules, which is a prerequisite for Tree-shaking.
Make sure your Webpack version is 4 or higher, because Tree-shaking was introduced in Webpack4.
Enable production mode in the Webpack configuration file, which turns on Webpack's optimization modes, including Tree-shaking.
Make sure that the optimization attribute in the Webpack configuration has enabled the minimize option, because Tree-shaking is performed during the code compression phase.
Make sure the sideEffects property in package.json is properly configured to avoid accidentally removing code with side effects. For example, resources like CSS files have side effects that need to be explicitly declared in sideEffects.

const path = require('path');

module.exports = {
    
    
  mode: 'production',
  entry: './src/index.js',
  output: {
    
    
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
  optimization: {
    
    
    minimize: true,
  },
};

In this configuration file, we set the mode to production, enabling Webpack's optimized mode. The optimization.minimize option defaults to true, which means that Webpack will automatically enable Tree-shaking during the packaging process

Guess you like

Origin blog.csdn.net/u013194063/article/details/130339437