Webpack4 learning notes – optimization part (happypack and webpack’s own optimization)

Time:2020-3-12

happypack

Happypack can use multithreading to package files (the default CPU core number is – 1), which has a higher utilization rate of multi-core CPU.
New happypack (options) can generate corresponding loaders, such as configuration:

new Happypack({
   id: 'js',
   use: [{
     loader: 'babel-loader',
     options: {
       cacheDirectory: true
     }
   }]
 }),
 New happypack ({other loader configuration})

Configure in the loader of JS:

use:[{
   loader: 'Happypack/loader',
   options: {
       id: 'js'
     }
}],

Then the package of JS can utilize multithreading.
Note that when the project is small, multi-threaded packaging will slow down the packaging speed.
*Note: for multithreaded packaging, the old version of webpack uses webpack.optimize.uglifyjsplugin for file compression. This plug-in is single thread, and multithreaded compression can be realized by using paralleluglifyplugin plug-in*

When taking an old project to test happypack, we found a problem. Module.rules.use should have passed in an [array], but the incoming {object} would not have reported an error, but the packaging speed is very different

Code 1:

use:[{
  loader: 'babel-loader',
  options: {
    cacheDirectory: true
  }
}],

Code 2:

use:{
  loader: 'babel-loader',
  options: {
    cacheDirectory: true
  }
},

For the same project, code 1 configuration is more than 10 seconds faster than code 2 configuration, and no reason is found in the official document..


Optimization of Web pack

tree-shaking

The web pack production environment automatically deletes unused code, such as:


import math from 'xx'
math.add(1,2)

In the production environment, the packed code will not pack the math methods other than add.
Note that this item is only valid for import. If const math = require (‘xx ‘). Default is selected directly, all contents in math will be packed.

Scope hosting scope promotion

When the web pack is packaged, it will automatically omit the parts that can be simplified, such as:

let a=1,b=2,c=3
let d=a+b+c
console.log(d)

The packaged code is directly:

console.log(6)