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

如何自定义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 chunk app, so it outputs as app.js instead of the default main.js.
  • minSize: 0: This bypasses Webpack's default minimum chunk size requirement, ensuring even tiny dependencies from node_modules get split into lib.js (since you wanted to ignore size rules).
  • priority: 10: Makes sure your commons cache 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 from src/myapp.js
  • lib.js: All code pulled from node_modules

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:46:40