This is the seventh day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Now that we have solved the common webPack problems, let’s take a closer look at the packaging optimization strategy for WebPack.

Optimize construction speed

  1. The essence of using loader is to manipulate strings. Such string manipulation can be very performance – consuming. In many cases, loader cannot be optimized, but we can minimize the number of files to be processed.

    • Specific measures have been adoptedincludeSpecify a directory for loader to retrieve:
    // webpack.config.js
    const path = require("path")
    module.exports = {
        module: {
            rules: [{test: /\.css$/,
                    use: ['style-loader'].include: [
                        path.resolve(__dirname, 'src']}]}}Copy the code
  2. Using dynamic link libraries Dynamic link libraries can contain functions and data that are called to other modules, and we can use dynamic link libraries to optimize building speed. Why is building faster with DLLS? Since there are many third-party libraries that do not need to be changed during the WebPack build process, they will be re-compiled for each build. If you use a DLL, you only need to compile once. After that, the code will be extracted from the DLL and used without recompiling. Webpack comes with the DllPlugin for the dynamic link library, which is also very easy to use, just need to configure in the plugin:

    // webpack.config.js
    const path = requrie('path')
    const DllPlugin = require('webpack/lib/DllPlugin')
    module.exports = {
        plugins: [
            new DllPlugin({
                name: '_dll_[name]'.path: path.resolve(__dirname, '[name].manifest.json')]}})Copy the code
  3. Use multiple processes for packaging

    Webpack is based on Node, and its single-threaded model is not well suited to handling I/O intensive operations. When the number of files to be processed is very large, a single thread can only queue processing one by one. To solve this problem, use the multi-core feature of the computer to process multiple files at the same time by using worker or multi-process method, and finally send the processing results back to the main process. Available plugins are :HappyPack

    // webpack.config.js
    const path = require('path');
    const HappyPack = require('happypack');
    module.exports = {
        module: {
            rules: [{test: /\.js&/,
                    use: ['happypack/loader? id=babel'].include: [
                        path.resolve(__dirname, 'src']}]},plugins: [
            new HappyPack({
                id: 'babel'.loaders: ['babel-loader']]}})Copy the code
  4. In addition to building with multiple processes, you can also use multiple processes for code compression. ParallelUglifyPlugin is one of the plug-ins you can use

Optimize packaging quality

Above we talked about how to improve build speed and development efficiency during project testing. But obviously code quality is important when building production code, so let’s look at ways to optimize package quality

  1. Extract common code

    • The same library may be used during code development. For example, when developing SPA applications with React or Vue, each page has the same technology stack and code, resulting in a lot of duplicate code between these pages.
    • The purpose of extracting common code is the problem of reusing code between ending pages.
    • Separate out the code that is packaged repeatedly between pages, so that duplicate code only loads once while the user is browsing, and then the browser caches them and uses the cache directly when visiting the second page.
    • For this, WebPack has one built inCommonsChunkPluginPlug-ins that can extract common code during packaging
    // webpack.config.js
    const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
    module.exports = {
        plugins: [
            new CommonsChunkPlugin({
                // Chunk to be extracted
                chunks: [].name: "common"}})]Copy the code
  2. Tree Shaking and lazy loading, mentioned in the previous section, is another way to improve code quality. Tree Shaking “optimizes” lazy loading of code that is not used in context is a logical way to split up code packages and optimize first screen loading speed

  3. In addition to extracting common code,Tree Shaking and lazy loading, there are many ways to optimize package quality, such as:

    • Code compression: Webpackmode: "production"Plug-ins that already reference code compression are built in
    • Using CDN: Enter output/ EntrypublicPathAnd then put the packaged files into the CDN

conclusion

This section mainly introduces the webPack packaging optimization strategy.

  • Optimize construction speed
    • Narrow the module search
    • Using dynamic Link Libraries (DLLS)
    • Use multiple processes for packaging
    • Use multiple processes for code compression
  • Optimize packaging quality
    • Extract common code
    • Tree Shaking & Lazy loading
    • Code compression, using CDN, etc

There are many optimization strategies, but these methods cannot cover all business scenarios. For example, when packaging a project into production, packaging quality is more important than construction speed, so we need to develop optimization strategies for different scenarios

This article is the sixth in a series of learning Webpack from Scratch. Additional chapters can be found at 👇 :

Learn webPack5.x from scratch (1) Learn webpack5.x from scratch (2) Learn Webpack5.x from scratch (3) Learn Webpack5.x from scratch (4) Learn Webpack5.x from scratch (5) Learn Webpack5.x from scratch (6)