如何自定义Webpack 4默认输出代码块名称,生成lib.js与app.js?
Fixing Webpack Chunk Splitting: Output app.js and lib.js Instead of main.js
Hey there! I see you're trying to split your code into lib.js (for node_modules dependencies) and app.js (your business code), but Webpack's still spitting out main.js. Let's get this sorted out, ignoring those size-based optimization rules you mentioned.
What's Going Wrong in Your Current Config?
Your entry point uses the default chunk name (main) since you didn't explicitly name it. Also, Webpack's default splitChunks settings include size thresholds (like minSize: 20000) that might be preventing the split even if you've defined your cache group. Plus, the default cache groups could be interfering with your custom one.
Here's the Fixed Config
const path = require('path'); module.exports = { // Explicitly name your entry chunk "app" so it outputs as app.js entry: { app: "./src/myapp.js" }, output: { path: path.resolve(__dirname, 'build/js'), filename: "[name].js" }, optimization: { splitChunks: { // Disable size restrictions to split regardless of chunk size minSize: 0, cacheGroups: { // Your custom group for node_modules dependencies commons: { test: /[\\/]node_modules[\\/]/, name: "lib", chunks: "all", // Give this group higher priority than default groups priority: 10 }, // Disable the default cache group to avoid conflicts default: false } } } };
Key Changes Explained
- Named Entry Chunk: By setting
entry: { app: "./src/myapp.js" }, we tell Webpack to name your business code chunkapp, so it outputs asapp.jsinstead of the defaultmain.js. minSize: 0: This bypasses Webpack's default minimum chunk size requirement, ensuring even tiny dependencies fromnode_modulesget split intolib.js(since you wanted to ignore size rules).priority: 10: Makes sure yourcommonscache group takes precedence over any default groups that might try to bundle dependencies differently.default: false: Disables Webpack's default cache group, which would otherwise potentially merge small chunks or override your custom splitting logic.
Test It Out
Run your Webpack build now, and you should see two files in build/js:
app.js: Your business code fromsrc/myapp.jslib.js: All code pulled fromnode_modules
内容的提问来源于stack exchange,提问作者andbi
相关产品推荐
相关产品推荐

