SoFunction
Updated on 2025-02-28

Webpack optimization tips that must be found in the front-end

Webpack optimization is necessary

The previous article explained it to you brieflyBuild a Vuecli, but it is only a basic construction without further optimization.

What can't be avoided with webpack packaging iswebpack optimizationOptimization is very important for this topic, whether it is interview or actual development. After all, improving user experience is the responsibility of our front-end engineers

Build time optimization

The first is the optimization of the build time

thread-loader

Multi-process packaging can greatly improve the speed of construction. The method is to use itthread-loaderBefore a time-consuming loader, for examplebabel-loader

Since both startup and packaging projects require acceleration, the configuration

npm i thread-loader -D
// 
{
        test: /\.js$/,
        use: [
          'thread-loader',
          'babel-loader'
        ],
      }
}

cache-loader

Cache resources to increase the speed of secondary construction, the method is tocache-loaderBefore a time-consuming loader, for examplebabel-loader

Since both startup and packaging projects require acceleration, the configuration

npm i cache-loader -D
// 
{
        test: /\.js$/,
        use: [
          'cache-loader',
          'thread-loader',
          'babel-loader'
        ],
},

Turn on hot updates

For example, if you modify a file in the project, it will cause the entire project to be refreshed, which is very time-consuming. If you only refresh the modified module and keep the rest intact, it will greatly increase the rebuild time of modifying the code

Only used in development, so the configuration is

// 
//Introduce webpackconst webpack = require('webpack');
//Use the hot update plugin provided by webpack   plugins: [
   new ()
    ],
    // Finally, it needs to be configured in our devserver     devServer: {
+     hot: true
    },

exclude & include

exclude: Files that do not need to be processed

include: Files that need to be processed

Setting these two properties reasonably can greatly improve the construction speed

existMedium configuration

// 
      {
        test: /\.js$/,
        //Use include to specify the compiled folder        include: (__dirname, '../src'),
        //Use exclude specified folder        exclude: /node_modules/,
        use: [
          'babel-loader'
        ]
      },

Build differentiated environments

It is very important to distinguish the environment to build. We must clearly know what configurations we need and what configurations we don’t need when developing the environment; and what configurations we need and what configurations we don’t need when finally packaging the production environment:

  • Development environment: Remove optimized configurations such as code compression, gzip, volume analysis, etc., greatly improve the construction speed
  • Production environment: Optimized configurations such as code compression, gzip, volume analysis, etc. are required to greatly reduce the packaging volume of the final project

The previous article has taken you to distinguish the environment

Improve webpack version

The newer the webpack version, the better the packaging effect

Packaging volume optimization

It is mainly optimized for the overall volume of the project after packaging, which is conducive to improving the page loading speed after the project is launched.

This project is already the latest version of webpack

CSS code compression

CSS code compression usecss-minimizer-webpack-plugin, the effects include compression and deduplication

The compression of the code is time-consuming, so it is only used when packaging the project, so it only needs to beMedium configuration

npm i css-minimizer-webpack-plugin -D
// 
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
  optimization: {
    minimizer: [
      new CssMinimizerPlugin(), // Deduplication compression css    ],
  }

JS code compression

JS code compression useterser-webpack-plugin, implement the compression of packaged JS code

The compression of the code is time-consuming, so it is only used when packaging the project, so it only needs to beMedium configuration

npm i terser-webpack-plugin -D
// 
const TerserPlugin = require('terser-webpack-plugin')
  optimization: {
    minimizer: [
      new CssMinimizerPlugin(), // Deduplication compression css      new TerserPlugin({ // Compress JS code        terserOptions: {
          compress: {
            drop_console: true, // Remove console          },
        },
      }), // Compress JavaScript    ],
  }

tree-shaking

tree-shakingSimply put, the function is: only package the used code, but not the used code, andwebpack5On by defaulttree-shaking, when packedmodeforproductionWhen it is automatically turned ontree-shakingPerform optimization

 = {
  mode: 'production'
}

source-map type

source-mapThe function is: to facilitate you to locate the error code when you report an error. Its size cannot be underestimated, so it is necessary to set different types in different environments.

  • Development Environment

When developing the environment, we need to be able to accurately locate the location of the error code.

// 
 = {
  mode: 'development',
  devtool: 'eval-cheap-module-source-map'
}
  • Production environment

Production environment, we want to open itsource-map, but don't want to be too large, so you can change the type

// 
 = {
  mode: 'production',
  devtool: 'nosources-source-map'
}

Packaging volume analysis

usewebpack-bundle-analyzerThe volume distribution after packaging can be reviewed and the corresponding volume optimization can be performed.

Just look at the volume when packing, so justMedium configuration

npm i webpack-bundle-analyzer -D
// 
const {
  BundleAnalyzerPlugin
} = require('webpack-bundle-analyzer')
  plugins: [
    new BundleAnalyzerPlugin(),
]

User experience optimization

Lazy loading of modules

If the module is not lazy to load, the entire project code will be packaged into a js file. The single js file is very large. Then when the user requests the web page, the first screen loading time will be relatively long. After using the module to load, the large js file will be divided into multiple small js files. The web page will be loaded as needed, greatly improving the first screen loading speed

// src/router/
const routes = [
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/home',
    name: 'home',
    // Lazy loading    component: () => import('../views/home/'),
  },
]

Gzip

After turning on Gzip, the user's page loading speed is greatly improved, because the volume of gzip is much smaller than the original file, of course, it requires the cooperation of the backend.compression-webpack-plugin

Just optimize the volume when packing, so justMedium configuration

npm i compression-webpack-plugin -D
// 
const CompressionPlugin = require('compression-webpack-plugin')
  plugins: [
    // Previous code...    // gzip
    new CompressionPlugin({
      algorithm: 'gzip',
      threshold: 10240,
      minRatio: 0.8
    })
  ]

Small picture to base64

For some small pictures, you can transfer to base64, which can reduce the number of http network requests on users and improve the user's experience.webpack5middleurl-loaderHas been abandoned and replacedasset-module

existMedium configuration

// 
{
   test: /\.(png|jpe?g|gif|svg|webp)$/,
   type: 'asset',
   parser: {
     // Conditions for base64     dataUrlCondition: {
        maxSize: 25 * 1024, // 25kb
     }
   },
   generator: {
     // Package into image file    filename: 'images/[contenthash][ext][query]',
   },
},

Configure hash reasonably

We must ensure that the modified files need to be updated with the hash value, while the unchanged files still maintain the original hash value. This ensures that after going online, files that have not changed when accessed by the browser will hit the cache, thereby achieving the purpose of performance optimization

existMedium configuration

// 
  output: {
    path: (__dirname, '../dist'),
    // Add contenthash to the js file    filename: 'js/chunk-[contenthash].js',
    clean: true,
  },

The above is the detailed content of the Webpack optimization techniques that must be learned on the front-end. For more information about the Webpack optimization techniques on the front-end, please pay attention to my other related articles!