webpack4.29.x Road to God (13) Tree shaking optimization

Previous section:  source-map

The contents of the previous section are as follows:

clipboard.png

concept

Official: Describe the removal of unreferenced code in the JavaScript context.
That is to say, we hope that webpack deletes unused functions when packaging, and the most common ones are third-party libraries: lodash, date-fns, etc.

Create a new src/js/math.js:

export function add(...arg) {
  return arg.reduce((x, y) => x + y);
}

export function sub(...arg) {
  return arg.reduce((x, y) => x - y);
}

Two functions are defined here, and then src/index.js is modified:

import {add} from './js/math';

console.log(add(2, 4, 11));

Modify the mode option of webpack.config.js and change production to development:

// 省略
mode: 'development',
// 省略

After packaging, the code will not be compressed.
Then npm run build, the editor opens bundles/main.js, and scrolls to the end:

clipboard.png

It can be seen that although only the add method is used in index.js, webpack will still package all the methods exported in math.js, so tree shaking is used to solve this problem.

Turn on tree shaking

Add an attribute to
package.json: package.json:

// 省略
"sideEffects": false,
// 省略

If sideEffects is set to false, webpack will think that all unused functions have no side effects, even if they are deleted, it does not matter.

Modify wbpack.config.js:

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    filename: '[name].js',
    path: resolve(__dirname, 'bundles')
  },

  // 开启devServer
  devServer: {},


  optimization: {
    // 优化导出的模块
    usedExports: true
  },

  module: {
    rules: [{
      test: /\.(gif|jpg|jpeg|png|svg)$/,
      use: ['url-loader']
    }, {
      test: /\.less$/,
      use: ['style-loader', 'css-loader', 'postcss-loader', 'less-loader']
    }]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html'
    }),
    new CleanWebpackPlugin()
  ]
};

Then npm run build, package bundles/main.js:

clipboard.png

This comment indicates that webpack has identified which methods are actually used, but continue to look at line 111:

clipboard.png

These two methods are still there, which means that this time the packaging is only marking the methods used, and the effect of tree shaking did not take effect. This is because the packaging mode just now is development. In the case of mode === develpoment, it is necessary Source-map debugging, if you delete the code, the mark position of the source-map will be inaccurate, so you can only try tree shaking in production mode.
Modify webpack.config.js:

module.exports = {
  mode: 'production',
  entry: './src/index.js',
  output: {
    filename: '[name].js',
    path: resolve(__dirname, 'bundles')
  },

  // 开启devServer
  devServer: {},


  // optimization: {
  //   // production模式下默认开启
  //   usedExports: true
  // },

  module: {
    rules: [{
      test: /\.(gif|jpg|jpeg|png|svg)$/,
      use: ['url-loader']
    }, {
      test: /\.less$/,
      use: ['style-loader', 'css-loader', 'postcss-loader', 'less-loader']
    }]
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './index.html'
    }),
    new CleanWebpackPlugin()
  ]
};

Npm run build again:

clipboard.png

The code is compressed, we can search reduce by ctrl + f and find that only the add method and the sub are removed, so tree shaking takes effect

Precautions

In the actual project, if the method we wrote ourselves is not used, there will be basically no problem, but the third-party modules and styles are hard to say, such as introducing in index.js:

clipboard.png

In this way of global introduction, webpack will still be treated as unused modules and be tree shaking off. These codes are so-called codes with side effects. We must prohibit tree shaking of them.

Modify the sideEffects property of package.json:

// 省略

"sideEffects": [
    // 数组里列出黑名单,禁止shaking下列代码
    "@babel/polly-fill",
    "*.less",

    // 其它有副作用的模块
    "./src/some-side-effectful-file.js"
  ],


//省略

In this way, tree shaking will not delete the code by mistake.

Next section: Distinguish between development and production environments

Guess you like

Origin blog.csdn.net/sd19871122/article/details/108182396