阿里云主机折上折
  • 微信号
Current Site:Index > The SplitChunksPlugin code splitting strategy

The SplitChunksPlugin code splitting strategy

Author:Chuan Chen 阅读数:16307人阅读 分类: 构建工具

SplitChunksPlugin Code Splitting Strategy

Webpack's SplitChunksPlugin is the core tool for optimizing code splitting. By intelligently separating common modules and third-party dependencies, it significantly improves application loading performance. Its core logic is based on configurable cache group strategies, allowing developers to precisely control code splitting behavior according to project requirements.

Basic Configuration Structure

The configuration of SplitChunksPlugin is located under the optimization.splitChunks node in webpack.config.js:

module.exports = {
  optimization: {
    splitChunks: {
      chunks: 'async',
      minSize: 30000,
      minChunks: 1,
      maxAsyncRequests: 5,
      maxInitialRequests: 3,
      automaticNameDelimiter: '~',
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true
        }
      }
    }
  }
}

Key Configuration Parameters Explained

Chunks Selection Strategy

Controls which types of modules participate in code splitting:

  • all: Both synchronously and asynchronously loaded modules are optimized
  • async (default): Only dynamically imported modules are optimized
  • initial: Only processes synchronously loaded modules
// Dynamic import example - processed by async strategy
import('lodash').then(_ => {
  console.log(_.VERSION)
})

Size Control Parameters

  • minSize (default 30000): Minimum size (in bytes) for generated chunks
  • maxSize: Attempts to split chunks larger than this value into smaller chunks
  • minChunks (default 1): Minimum number of references threshold
// This utility function will only be split when used by two or more files
const utils = {
  formatDate: date => date.toISOString()
}

Request Limit Parameters

  • maxAsyncRequests (default 5): Maximum number of parallel async requests
  • maxInitialRequests (default 3): Maximum number of initial requests at entry points

Cache Group Strategy

Cache groups are the most powerful feature of SplitChunksPlugin, allowing the definition of multiple splitting rules:

Third-party Library Separation

Typical configuration to bundle node_modules separately:

cacheGroups: {
  vendor: {
    test: /[\\/]node_modules[\\/]/,
    name: 'vendors',
    chunks: 'all'
  }
}

Business Code Splitting

Example of splitting by business module:

cacheGroups: {
  userModule: {
    test: /[\\/]src[\\/]modules[\\/]user/,
    name: 'user-module',
    priority: 10
  },
  productModule: {
    test: /[\\/]src[\\/]modules[\\/]product/,
    name: 'product-module',
    priority: 10
  }
}

Runtime Optimization

Extracting webpack runtime code:

runtimeChunk: {
  name: entrypoint => `runtime-${entrypoint.name}`
}

Advanced Optimization Techniques

Module Duplication Detection

Avoid duplicate bundling with reuseExistingChunk:

cacheGroups: {
  common: {
    minChunks: 2,
    reuseExistingChunk: true
  }
}

Priority Control

Resolve rule conflicts using priority:

cacheGroups: {
  libs: {
    test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
    priority: 20
  },
  vendors: {
    test: /[\\/]node_modules[\\/]/,
    priority: -10
  }
}

Dynamic Naming Strategy

Generate hash names based on module content:

name(module, chunks, cacheGroupKey) {
  const moduleFileName = module.identifier().split('/').reduceRight(item => item);
  return `${cacheGroupKey}-${moduleFileName}`;
}

Performance Trade-off Strategies

Granularity Control

Over-splitting increases requests, while under-splitting loses optimization benefits. Recommended strategy:

// Set different minSize based on file type
cacheGroups: {
  scripts: {
    test: /\.js$/,
    minSize: 100000
  },
  styles: {
    test: /\.css$/,
    minSize: 50000
  }
}

Long-term Caching Optimization

Combine with contenthash for persistent caching:

output: {
  filename: '[name].[contenthash:8].js',
  chunkFilename: '[name].[contenthash:8].chunk.js'
}

Debugging and Analysis Tools

Visualization Analysis

Use webpack-bundle-analyzer to inspect splitting results:

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

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

Statistics Output

Get detailed splitting data via stats:

webpack --profile --json > stats.json

Multi-page Application Strategy

Extract common dependencies for each entry:

cacheGroups: {
  commons: {
    name: 'commons',
    chunks: 'initial',
    minChunks: 2,
    minSize: 0
  }
}

Framework-specific Optimizations

React Application Optimization Example

cacheGroups: {
  react: {
    test: /[\\/]node_modules[\\/](react|react-dom|react-router)[\\/]/,
    name: 'react-bundle',
    chunks: 'all'
  },
  redux: {
    test: /[\\/]node_modules[\\/](redux|react-redux|redux-thunk)[\\/]/,
    name: 'redux-bundle',
    chunks: 'all'
  }
}

Vue Application Optimization Example

cacheGroups: {
  vue: {
    test: /[\\/]node_modules[\\/](vue|vue-router|vuex)[\\/]/,
    name: 'vue-bundle',
    chunks: 'all'
  },
  elementUI: {
    test: /[\\/]node_modules[\\/]element-ui[\\/]/,
    name: 'element-ui',
    chunks: 'all'
  }
}

Practical Scenario Solutions

Solving moment.js Locale Issue

cacheGroups: {
  moment: {
    test: /[\\/]node_modules[\\/]moment[\\/]/,
    name: 'moment',
    chunks: 'all',
    enforce: true
  }
}

On-demand Loading Optimization

Combine with dynamic imports for route-level splitting:

const UserPage = () => import(/* webpackChunkName: "user" */ './views/UserPage.vue')

Configuration Validation Methods

Ensure configuration correctness with webpack-validator:

const validate = require('webpack-validator')

module.exports = validate({
  // webpack configuration
})

Version Compatibility Notes

Handling differences between webpack versions:

  • webpack 4+: Out-of-the-box default configuration
  • webpack 5: New chunkIds and moduleIds algorithm options
optimization: {
  chunkIds: 'deterministic',
  moduleIds: 'deterministic'
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.