Preliminary performance optimization of webpack

Performance optimization of development environment

  • Optimize packaging build speed (HMR)
    HMR:hot module Replacement hot module replacement: when one module changes, only the changed modules will be repackaged, not all modules, to improve the construction speed
    1. The style file can use the HMR function, as long as the style loader is used in the loader
 {
    // Processing css resources
      test: /\.css$/,
      use: ['style-loader', 'css-loader']
    }

2. js files cannot use the HMR function by default. You need to modify js to add code that supports the HMR function, but you can only process other files that are not entry js files

if (module.hot) {
  // Once module.hot  true indicates that the HMR function is enabled. -->Let HMR function code take effect
  module.hot.accept('./print.js', function() {
    // Method will listen print.js  Once the file changes, other modules will not be repackaged and built.
    // The following callback function will be executed
    print();
  });
}

3. HTML files cannot use HMR by default. Generally, no hot update is required.

entry: ['./src/js/index.js', './src/index.html'],
  • Optimize code debugging (source map)
    Source map: a technology that provides mapping of source code to post build code (if there is a post build code error, you can trace the source code error through mapping)
devtool: 'eval-source-map'
type Scope of action
source-map Mapping individual external files, error code accurate information and source code error location
inline-source-map Map a single inline source map, error code accuracy and source code error location
hidden-source-map Map a separate external file, error code error reason, but there is no error location, unable to trace the source code error, can only prompt the error location of the built code
eval-source-map Each file generates a corresponding source map, which is in the error code of eval and the error location of the source code
nosources-source-map The error code is accurate, but there is no source code information
cheap-source-map Error code accurate information and source code error location can only be accurate to line
cheap-module-source-map Error code accuracy information and source code error location

Performance optimization of production environment

  • Optimize packaging build speed
    1,oneOf
    When a file only needs to be processed by one loader, only one loader will be matched with oneOf
 oneOf: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
          },
   ]

2. Multiprocess packaging

Open multi process packaging. Only when the working time is long, multi process packaging is needed

 {
     loader: 'thread-loader',
      options: {
        workers: 2 // 2 processes
      }
    }

3,externals

Exclude non packing files

externals: {
    // Refuse to package jQuery
    jquery: 'jQuery'
  }

4,dll

(1) Need to run webpack.dll.js file

Using dll technology, for some libraries (third-party libraries: jquery, react, vue...) Pack separately
When you run webpack, the default lookup webpack.config.js configuration file
–> webpack --config webpack.dll.js

 plugins: [
    // Package to build a manifest.json  -->Provide and jquery mapping
    new webpack.DllPlugin({
      name: '[name]_[hash]', // Exposed content name of the mapping Library
      path: resolve(__dirname, 'dll/manifest.json') // Output file path
    })
  ],

(2) Tell webpack which libraries are not involved in packaging, and the name of the library must be changed

 new webpack.DllReferencePlugin({
      manifest: resolve(__dirname, 'dll/manifest.json')
    }),

(3) Package and output a file and automatically import the resource into html

 new AddAssetHtmlWebpackPlugin({
      filepath: resolve(__dirname, 'dll/jquery.js')
    })
  • Optimize code performance
    1. Cache (hash chunkhash content hash)

babel cache setting cacheDirectory: true can make the second package build faster

 // On the second build, the previous cache is read
  cacheDirectory: true

File resource cache
(1) Hash: a unique hash value is generated each time the wepack is built.
Problem: because js and css use a hash value at the same time.
(2) Chunk hash: hash value generated from chunk. If the package comes from the same chunk, the hash value is the same
Problem: the hash values of js and css are the same
Because css is introduced in js, it belongs to the same chunk
(3) Content hash: generates a hash value based on the content of the file. The hash value of different files must be different

  output: {
    filename: 'js/built.[contenthash:10].js',
    path: resolve(__dirname, 'build')
  }

2,tree shaking

Tree shaping: remove useless code;
Premise: 1. ES6 modularization must be used; 2. Open the production environment
Effect: reduce code volume
Problem: the css / @babel/polyfill file may be deleted
stay package.json Configure "sideEffects": [". css", ".less"]

"sideEffects": [
    "*.css"
  ]

3,code spilt
(1) Configure entry / / entry

// Single entry
  // entry: './src/js/index.js',
  entry: {
    // Multiple entry: with one entry, the final output has a bundle
    index: './src/js/index.js',
    test: './src/js/test.js'
  },

(2) Setting optimization

/*
    1. Nodes can be_ The code in modules is packaged with a chunk for final output
    2. Automatically analyze whether there are public files in the multi entry chunk. If any, it will be packaged as a single chunk
  */
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  },

(3) Import dynamic import syntax

/*
  Through js code, let a file be individually packaged into a chunk
  import Dynamic import syntax: can package a file separately
*/
import(/* webpackChunkName: 'test' */'./test')
  .then(({ mul, count }) => {
    // File loaded successfully~
    // eslint-disable-next-line
    console.log(mul(2, 5));
  })
  .catch(() => {
    // eslint-disable-next-line
    console.log('File load failed~');
  });

4. Lazy load preload

//Lazy load: load only when the file needs to be used
//Preload: js files will be loaded in advance before use
//Normal loading can be considered as parallel loading (loading multiple files at the same time)
//Preload prefetch: after other resources are loaded, the browser is idle, and then the resources are loaded secretly

import(/* webpackChunkName: 'test', webpackPrefetch: true */'./test').then(({ mul }) => {
    console.log(mul(4, 5));
  });

5,PWA

PWA: Progressive web development applications(Offline accessible)
workbox --> workbox-webpack-plugin

 new WorkboxWebpackPlugin.GenerateSW({
      /*
        1. Help serviceworker to start quickly
        2. Delete old serviceworker

        Generate a serviceworker configuration file~
      */
      clientsClaim: true,
      skipWaiting: true
    })

Tags: Webpack JQuery JSON hot update

Posted on Wed, 24 Jun 2020 02:50:40 -0400 by ConnorSBB