SoFunction
Updated on 2025-04-14

Summary of Webpack packaging speed optimization solutions

1. Basic configuration optimization

1.1 Distinguish between development and production environments

// 
 = (env, argv) => {
  const isProduction =  === 'production';
  
  return {
    mode: isProduction ? 'production' : 'development',
    devtool: isProduction ? 'source-map' : 'eval-cheap-module-source-map',
    // Other configurations...  };
};

Optimization point

  • Faster sourcemap generation methods in development environments
  • Enable full optimization in production environment but retain sourcemap

1.2 Reduce the resolution range

 = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        include: (__dirname, 'src'),
        use: ['babel-loader']
      }
    ]
  },
  resolve: {
    modules: [(__dirname, 'src'), 'node_modules'],
    extensions: ['.js', '.jsx'] // Try to reduce extension  }
};

2. Loader optimization strategy

2.1 Limit the loader application scope

{
  test: /\.js$/,
  exclude: /node_modules/,
  include: (__dirname, 'src'),
  use: ['babel-loader?cacheDirectory']
}

2.2 Enable loader cache

use: [
  {
    loader: 'babel-loader',
    options: {
      cacheDirectory: true // Default cache directory node_modules/.cache/babel-loader    }
  }
]

2.3 Reduce the number of loaders

// Avoid unnecessary loader calls{
  test: /\.(jpe?g|png|gif|svg)$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        limit: 8192 // less than 8KB to base64      }
    }
    // Remove unnecessary image-webpack-loader development environment  ]
}

3. Plug-in optimization solution

3.1 Selective use of plug-ins

const plugins = [
  new ({/*...*/}),
  isProduction && new MiniCssExtractPlugin()
].filter(Boolean);

3.2 Disable development useless plug-ins

plugins: [
  !isDevelopment && new CompressionPlugin(),
  !isDevelopment && new BundleAnalyzerPlugin()
].filter(Boolean)

3.3 Using HardSourceWebpackPlugin

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

 = {
  plugins: [
    new HardSourceWebpackPlugin()
  ]
};

Effect: The secondary construction speed is increased by 60%-80%

4. Module analysis and optimization

4.1 Reduce the search scope of modules

resolve: {
  alias: {
    '@': (__dirname, 'src'),
    react: (__dirname, './node_modules/react')
  },
  symlinks: false // Prevent duplicate parsing caused by npm link}

4.2 Use

module: {
  noParse: /jquery|lodash/ // Ignore unmodulated libraries}

5. Multi-process parallel processing

5.1 thread-loader

 = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: 'thread-loader',
            options: {
              workers: 2,
              workerParallelJobs: 50,
              poolTimeout: 2000
            }
          },
          'babel-loader'
        ]
      }
    ]
  }
};

5.2 parallel-webpack

// Run directly after installationparallel-webpack --config=

5.3 TerserPlugin Multi-process

optimization: {
  minimizer: [
    new TerserPlugin({
      parallel: require('os').cpus().length - 1
    })
  ]
}

6. Specialized optimization of development environment

6.1 Disable production environment optimization

optimization: {
  removeAvailableModules: false,
  removeEmptyChunks: false,
  splitChunks: false,
  minimize: false
}

6.2 Using cache-loader

{
  test: /\.(js|jsx)$/,
  use: [
    'cache-loader',
    'babel-loader'
  ],
  include: ('src')
}

6.3 Incremental Compilation

watchOptions: {
  aggregateTimeout: 500, // Anti-shake delay  ignored: /node_modules/ // Ignore the directory}

7. DLL precompilation technology

7.1 Create a DLL configuration

// 
 = {
  entry: {
    vendor: ['react', 'react-dom', 'lodash']
  },
  output: {
    filename: '[name].',
    path: (__dirname, 'dll'),
    library: '[name]_[hash]'
  },
  plugins: [
    new ({
      name: '[name]_[hash]',
      path: (__dirname, 'dll', '[name]-')
    })
  ]
};

7.2 Master configuration reference DLL

// 
plugins: [
  new ({
    manifest: require('./dll/')
  })
]

8. Advanced optimization skills

8.1 Use SWC to replace Babel

module: {
  rules: [
    {
      test: /\.(js|jsx)$/,
      exclude: /node_modules/,
      use: {
        loader: 'swc-loader',
        options: {
          jsc: {
            parser: {
              syntax: 'ecmascript',
              jsx: true
            }
          }
        }
      }
    }
  ]
}

Speed ​​comparison: SWC is more than 20 times faster than Babel

8.2 Using esbuild-loader

const { ESBuildMinifyPlugin } = require('esbuild-loader');

 = {
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'esbuild-loader',
        options: {
          target: 'es2015'
        }
      }
    ]
  },
  optimization: {
    minimizer: [
      new ESBuildMinifyPlugin({
        target: 'es2015'
      })
    ]
  }
};

8.3 Module Federated Sharing

// Shared dependencies avoid duplicate packagingnew ModuleFederationPlugin({
  name: 'app1',
  shared: {
    react: { singleton: true },
    'react-dom': { singleton: true }
  }
})

9. Build an analysis tool

9.1 Speed ​​analysis

const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();

 = ({
  // Original webpack configuration});

9.2 Construction time-consuming analysis

class BuildTimePlugin {
  apply(compiler) {
    let startTime;
    
    ('BuildTime', () => {
      startTime = ();
    });
    
    ('BuildTime', stats => {
      (`Time-consuming to build: ${(() - startTime) / 1000}s`);
    });
  }
}

10. Comprehensive optimization configuration example

const path = require('path');
const os = require('os');
const webpack = require('webpack');
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

 = {
  mode: 'development',
  devtool: 'eval-cheap-module-source-map',
  cache: {
    type: 'filesystem',
    buildDependencies: {
      config: [__filename]
    }
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'thread-loader',
            options: {
              workers: ().length - 1
            }
          },
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new HardSourceWebpackPlugin(),
    new (),
     && new BundleAnalyzerPlugin()
  ].filter(Boolean),
  resolve: {
    alias: {
      '@': ('src')
    },
    extensions: ['.js', '.json']
  },
  optimization: {
    removeAvailableModules: false,
    removeEmptyChunks: false,
    splitChunks: false,
    minimize: false
  },
  stats: {
    modules: false,
    children: false,
    chunks: false,
    chunkModules: false
  }
};

Comparison of key optimization indicators

Optimization means Build time reduction Applicable scenarios
HardSourceWebpackPlugin 60%-80% Development Environment
thread-loader 30%-50% Large-scale projects
DLL precompilation 40%-60% Stable third-party library
SWC/esbuild 50%-70% Full scene
Cache configuration 70%-90% Incremental construction

Best Practice Recommendations

  • Hierarchical optimization

    • Development environment: Focus on construction speed (cache, non-compression)
    • Production environment: Focus on output quality (Tree Shaking, compression)
  • Progressive implementation

1. Add basic cache(HardSourceWebpackPlugin)
2. Introducing multi-process(thread-loader)
3. Analysis and optimization focus(SpeedMeasurePlugin)
4. Implement advanced optimization(DLL/SWC)

Continuous monitoring

  • Record each build time
  • Setting up performance budget
performance: {
  hints: 'warning',
  maxAssetSize: 500 * 1024,
  maxEntrypointSize: 500 * 1024
}

By comprehensively applying these optimization strategies, Webpack build speed can be increased by 3-10 times, significantly improving the development experience. It is recommended to use selectively and combine them according to the actual situation of the project, and regularly use analysis tools to evaluate the optimization effect.

The above is the detailed content of the Webpack packaging speed optimization solution. For more information about Webpack packaging speed optimization, please pay attention to my other related articles!