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 (page1andpage2)—this is crucial for targeting later.splitChunks.default: falseandsplitChunks.vendors: false: Disables Webpack's default behavior of splitting shared code and general vendor code, which prevents unwanted splits betweenpage1andpage2.cacheGroups.page2Vendors:test: Ensures we only match modules fromnode_modules.chunks: chunk => chunk.name === 'page2': The magic line—this restricts the split exclusively to thepage2entry chunk, ignoringpage1entirely.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 frompage1.jsand its dependencies (including any shared code withpage2—no splitting here).page2.js: Contains only the business logic frompage2.js(excludingnode_modulescode).page2-vendors.js: Contains allnode_modulesdependencies used bypage2.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
相关产品推荐
相关产品推荐

