webpack 分包,如何把模块和依赖打包在一起

问题出现的环境背景

Webpack v5

问题描述

主入口 index.js 引用 components 目录下的 a 模块和 b 模块,a 模块中引用 c 模块,index.js 中并未直接引用 c 模块。

想要把 components 目录下用到的模块以及它们的依赖打包在一起。

相关代码

// webpack.config.js
const path = require("path");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
  .BundleAnalyzerPlugin;

module.exports = {
  mode: "production",
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "dist")
  },
  optimization: {
    runtimeChunk: "single",
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]components[\\/]/,
          name: "vendors",
          chunks: "all",
          priority: 10,
          enforce: true,
          reuseExistingChunk: true
        }
      }
    }
  },
  plugins: [
    new BundleAnalyzerPlugin({
      openAnalyzer: false
    })
  ]
};

得到的结果,c 模块进了主 bundle
Screen Shot 2021-08-03 at 6.22.51 PM.png

Project Code:https://codesandbox.io/s/sill...
Preview:https://k6gew.sse.codesandbox...

你期待的结果是什么?实际看到的错误信息又是什么?

期望 c 模块优先和自定义模块打包在一起,能怎么实现呢?

回复
阅读 1.4k
1 个回答

因为c.js是直接在src下,vendor的判断条件不会匹配到c.js

可以通过修改test来匹配到c.js,从而让c.js也能打包进vendor

module.exports = {
  // ...
  optimization: {
    runtimeChunk: 'single',
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]components[\\/]|[\\/]src[\\/]c\.js/,
          name: 'vendors',
          chunks: 'all',
          priority: 10,
          enforce: true,
          reuseExistingChunk: true,
        },
      },
    },
  },
  // ...
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏