You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Webpack 4中如何仅对单个入口做splitChunks?提取page2的node_modules代码

Solution for Targeted SplitChunks in Webpack 4

Got it, let's break down how to achieve exactly what you need: extract only the node_modules code used by page2.js, while leaving shared code between page1.js and page2.js untouched.

The key is to use Webpack 4's splitChunks configuration with targeted chunk filtering in cacheGroups. Here's a complete, ready-to-use config:

module.exports = {
  entry: {
    page1: './src/page1.js',
    page2: './src/page2.js'
  },
  output: {
    filename: '[name].js',
    path: __dirname + '/dist'
  },
  optimization: {
    splitChunks: {
      // Disable default cacheGroups to avoid automatic shared code splitting
      default: false,
      vendors: false,
      cacheGroups: {
        // This group handles only page2's node_modules dependencies
        page2Vendors: {
          // Match all modules from node_modules
          test: /[\\/]node_modules[\\/]/,
          // Only apply this split to the 'page2' entry chunk
          chunks: chunk => chunk.name === 'page2',
          // Name the output chunk for clarity
          name: 'page2-vendors',
          // Enforce this split regardless of Webpack's default thresholds
          enforce: true,
          // Set higher priority to override any other potential cache groups
          priority: 10
        }
      }
    }
  }
};

What each part does:

  • entry: Defines your two entry points with clear names (page1 and page2)—this is crucial for targeting later.
  • splitChunks.default: false and splitChunks.vendors: false: Disables Webpack's default behavior of splitting shared code and general vendor code, which prevents unwanted splits between page1 and page2.
  • cacheGroups.page2Vendors:
    • test: Ensures we only match modules from node_modules.
    • chunks: chunk => chunk.name === 'page2': The magic line—this restricts the split exclusively to the page2 entry chunk, ignoring page1 entirely.
    • enforce: true: Forces the split even if the vendor code doesn't meet Webpack's default thresholds (like minimum chunk size), ensuring it always works as expected.
    • priority: 10: Makes sure this group takes precedence over any other custom cache groups you might add later.

Result:

  • page1.js: Contains all code from page1.js and its dependencies (including any shared code with page2—no splitting here).
  • page2.js: Contains only the business logic from page2.js (excluding node_modules code).
  • page2-vendors.js: Contains all node_modules dependencies used by page2.js.

This setup perfectly meets your requirement: no shared code extraction between the two entries, and only page2's vendor code gets split out.

内容的提问来源于stack exchange,提问作者Chef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:57:40