Primary analysis: Use stats built into WebPack

Stats: Build statistics

Use stats in package.json

"scripts": {
    "build:stats":"webpack --env production --json > stats.json"
}
Copy the code

Specify the output JSON object, output a JSON file

Used in the Node. Js

const webpack = require('webpack')
const config = require('./webpack.config.js') ('production')

webacpk(config, (err, stats) => {
    if(err) {
        return console.error(err);
    }
    
    if(stats.hasErrors()) {
        return console.log(stats.toString("errors-only"))
    }
    
    console.log(stats);
     
})
Copy the code

Disadvantages: the granularity is too thick to see the problem.

Speed analysis: use speed-measure-webpack-plugin

const SpeedMeasureWebpackPlugin = require('speed-measure-webpack-plugin')

const smp = new SpeedMesurePlugin();

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

Speed analysis plug-in functions

  • Analyze the total packaging time
  • Time consumption per plug-in and loader

Volume analysis: Use Webpack-bundle-Analyzer to analyze volumes

const {BundleAnalyzerPlugin} =require('webpack-bundle-analyzer')

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

After the build is complete, expand the size on port 8888

What problems can be analyzed?

  • Dependent third party module file size
  • The size of the component code in the business

Multi-process multi-instance build

Use thread-loader to parse resources

How it works: Each time webPack parses a module, Thread-Loader assigns it and its dependencies to worker threads

use:[
{
    loader:'thread-loader',
    options: {
        workers: 3
    }
}]
Copy the code

Parallel compression of multiple process instances

  • Method 1: Use the parallel ugliffe -plugin
const ParalleUglifyPlugin = require('parallel-uglify-plugin')

module.exports = {
    plugins: [
        new ParalleUglifyPlugin({
            uglifyJs:{
                output: {
                    beautify:false,
                    comments:false,
                },
                compress:{
                    warnings: false,
                    drop_console:true,
                    collapse_vars:true,
                    reduce_vars:true}}})]}Copy the code
  • Uglifyjs-webpack-plugin enables the PARALLEL parameter
plugins: [
    new UglifyJsPlugin({
        uglifyOptions:{},
        parallel:true})]Copy the code
  • Terser-webpack-plugin enables the PARALLEL parameter
module.exports = {
    optimization: {
        minimizer: [
            new TerserPlugin({
                parrallel:4
            })
        ]
    }
}
Copy the code

Further subcontracting: precompile resource modules

React-dom redux redux react-redux react-redux react-redux react-redux react-redux react-redux react-redux react-redux react-redux

Method: Create a separate configuration file, usually named webpack.dll.js, and use DLLPlugin for subcontracting. DllReferencePlugin references manifest.json.

const path = require('path')
const webpack = requrie('webpack')

module.exports = {
    context: process.cwd(),
    resolve:{
        extensions:['js'.'jsx'.'.json'.'.less'.'.css'],
        modules:[__dirname, 'node_modules']
    },
    entry: {
        library: [
        'react'.'react-dom'.'redux'.'react-redux']
    },
    output: {
        filename: '[name].dll.js',
        path: path.resolve(__dirname, './build/library'),
        library: '[name]'
    },
    plugins: [
        new webpack.Dllplygin({
            name: '[name]',
            path: './build/library/[name].json'}})]Copy the code

Introduced in webpack. Config. Js

module.exports = {
    plugins: [
        new webpack.DllReferencePlugin({
            mainfest:require('./build/library/mainfest.json')]}})Copy the code

Make full use of cache to improve secondary build speed

Cache idea:

  • Babel-loader enables caching
  • Terser-webpack-plugin enables caching
  • Use cache-loader or hard-source-webpack-plugin

Narrow your Build goals

Purpose: Build as few modules as possible

For example, Babel-laoder does not parse node_modules

module.exports = {
    rules: {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: 'node_modules'}}Copy the code

Reduce file search scope

  • Optimize the resolve.modules configuration (reduce the module search hierarchy)
  • Optimize the resolve.mainfields configuration
  • Optimize the resolve.extensions configuration
  • Use Aliases wisely
module.exports = {
    resolve: {
        alias: {
            react: path.resolve(__dirname, './node_modules/react/dist/react.min.js')
        },
        modules: [path.resolve(__dirname, 'node_modules')],
        extensions: ['js'],
        mainFilelds:['main'].}}Copy the code

Use Webpack for image compression

Requirements: Imagemin or tinypngAPI based on Node library

Use: configure image-webpack-loader

return {
    test: /\.(png|svg|jpg|gif)$/,
    use: [{
        loader:'file-loader'
        options:{
            name:  `${filename}img/[name]${hash}.[ext]`
        }
    },{
        loader:'image-webpack-loader',
        options: {
            mojpeg: {
                progressive: true,
                quality: 65
            },
            optipng: {
                enabled: false,}, pngquant: {quality:'65-90',
                speed: 4
            }
        }
        
    }]
}
Copy the code

Advantages of Imagemin point analysis

  • There are many customization options
  • More third-party optimization plug-ins, such as PngQuant, can be introduced
  • Can handle a variety of image formats

Use TreeShaking to erase useless CSS

How to delete useless CSS?

  • PurifyCSS: Iterates through the code to identify the CSS classes that have been used
  • Uncss :HTML is loaded via jsDOM, all styles are parsed through PostCSS, and document.querySelector is used to identify selectors that do not exist in HTML files.

How do I use PurifyCSS in Webpack?

  • Using purgecss – webpack – webpack – plugin (www.npmjs.com/package/pur)…
  • Use with mini-CSS-extract-plugin

Use the dynamic Polyfill service

  • Babel-polyfill (React16 Official Recommendation)
  • Polyfill-service (Community Maintenance)

Polyfill Service principle

Identify the User Agent and deliver different polyfills

Volume optimization strategy summary

  • Scope Hoisting
  • Tree-shaking
  • Separation of common resources
  • Image compression
  • Dynamic Polyfill

More articles

  • The Core Concepts of WebPack series (1)
  • Play webpack series file monitor, file fingerprint, code compression (2)
  • Play webpack series webpack advanced usage (3)