First, speed index

1. Webpack stats

Comparatively coarse granularity analysis construction speed

"build:stats": "webpack --profile --json=compilation-stats.json"
Copy the code

2. Speed – measure – webpack webpack – the plugin

  • Analyze the total packaging time
  • Time consumption per plug-in and loader
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");

const smp = new SpeedMeasurePlugin();

const webpackConfig = smp.wrap({
  plugins: [new MyPlugin(), new MyOtherPlugin()],
});
Copy the code

3. The webpack webpack – bundle – analyzer

  • Dependent third party module file size
  • The size of the component code in the business
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
}
Copy the code

Second, construction speed

1. Multi-process/multi-instance parsing resources: Thread-loader

  • Role: Improve build speed
  • How it works: Each time webPack parses a module, Thread-Loader assigns its dependencies to worker threads
{
    test: /.js$/,
    use: [
        {
            loader: 'thread-loader',
            options: {
                workers: 2
            }
        },
        'babel-loader'
    ]
},
Copy the code

2. Multi-process/multi-instance compression :terser-webpack-plugin

  • Role: Improve build speed
const TerserPlugin = require("terser-webpack-plugin");
optimization: {
    minimizer: [
        new TerserPlugin({
            parallel: true,
        })
    ],
},
Copy the code

Three, packaging volume

1.SplitChunksPlugin

Can be used to isolate common resources or common methods and reduce code size, for example:

module.exports = {
  //...
  optimization: {
    splitChunks: {
        cacheGroups: {
          commons: {
            test: /(react|react-dom)/,
            name: 'vendors',
            chunks: 'all',
          }
        },
    }
  },
};
Copy the code

2.three-shaking

Action: Erases the following code

  • Code will not be executed, not reachable
  • The results of code execution are not used
  • The code only affects dead variables (write, not read)

Principle: Using ES6 module characteristics, the code in ast stage for today’s analysis

  • Can only appear as a statement at the top level of a module
  • The module name for import must be a string constant
  • Import binding is immutable

Trigger: just turn on mode:’ Production ‘

3.Scope Hoisting

The code packaged by Webpack will exist in the form of closures. The scope collieries can reduce the function declaration overhead and memory overhead. Principle: Place all the modules’ code in a function scope according to the order of reference, and then rename some variables appropriately to prevent variable name conflicts.

  • Automatic: just turn on mode:’ Production ‘
  • Manual: Add the following code to your plugins
new webpack.optimize.ModuleConcatenationPlugin();
Copy the code

4. Code splitting and dynamic import

Webpack can break code into chunks and load them when the code runs until it is needed. The scenarios are:

  • Pull the same code into a shared block
  • The script loads lazily, making the initial download smaller

Activation:

  • Dynamic import is supported by default if @babel/preset-env is used in. Babelrc
{
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": []
}
Copy the code
  • If you were simply translating import, you would simply add @babel/plugin-syntax-dynamic-import to the plugins of.babelrc
{
    "presets": [],
    "plugins": [
        "@babel/plugin-syntax-dynamic-import"
    ]
}
Copy the code

This bag will do

5.CSS erasure: purgecss-webpack-plugin

const PurgeCSSPlugin = require('purgecss-webpack-plugin')
const PATHS = {
    src: path.join(__dirname, 'src')
}
// ...
plugins: [
    new PurgeCSSPlugin({
        paths: glob.sync(`${PATHS.src}/**/*`,  { nodir: true }),
    }),
]
Copy the code

6. Image compression :image-webpack-loader

rules: [{ test: /\.(gif|png|jpe?g|svg)$/i, use: [ 'file-loader', { loader: 'image-webpack-loader', options: { mozjpeg: { progressive: true, }, // optipng.enabled: false will disable optipng optipng: { enabled: false, }, pngquant: {quality: [0.65, 0.90], speed: 4}, GIFsicle: {interlaced: false,}, // The webp option will enable webp webp: { quality: 75 } } }, ], }]Copy the code

7. Dynamic Babel – pollyfill

Each device terminal may have different requirements for Babel-Pollyfill, or even do not need babel-Pollyfill. Therefore, dynamic Babel-Pollyfill needs to be loaded on demand at the judgment of the User Agent. Such as:

<script scr="http://cdn.polyfill.io/v2/polyfill.min.js"></script>
Copy the code

Summary: The current ways of building volume solutions are

  • 1.SplitChunksPlugin
  • 2.three-shaking
  • 3.Scope Hoisting
  • 4. Dynamic import is loaded on demand
  • 5.CSS erasure: purgecss-webpack-plugin
  • 6. Image compression :image-webpack-loader
  • 7. Dynamic Babel – pollyfill