Webpack 5 DependOn 仅在条目仅依赖一个依赖项时起作用

Webpack 5 DependOn only works when the entry depends on only one dependency

为了给你一些背景信息,我正在开发一个 .NET 核心应用程序,并且在其中一个 cshtml 中我正在注入一个 React 迷你应用程序,如下所示:

<div id="workshop" data-id=@Model></div>

<script src="~/bundles/js/workshop-bundle.js"></script>

它运行良好,但是当我使用 webpack 编译时,workshop 包太大(800kb)并且我收到了警告。 workshop-bundle 包括一些依赖项,如 axios、highcharts-react-official 和 highcharts/highmaps。所以我试着拆分包。

在 webpack.config.js 上,我正在尝试在其中一个条目中使用 DependOn。在这种情况下,workshop 依赖于 axios、highcharts-react-official 和 highcharts/highmaps,所以基于 webpack 文档我尝试了这个:

webpack.config.js

entry: {
    workshop: {
      import: "./wwwroot/component/WorkshopApp.tsx",
      dependOn: ["axios", "highmaps", "highchartreact"],
    },
    highchartreact: "highcharts-react-official",
    highmaps: "highcharts/highmaps",
    axios: "axios",
  },

.cshtml:

<div id="workshop" data-id=@Model></div>
<script src="~/bundles/js/axios-bundle.js"></script>
<script src="~/bundles/js/highchartreact-bundle.js"></script>
<script src="~/bundles/js/highmaps-bundle.js"></script>
<script src="~/bundles/js/workshop-bundle.js"></script>

它生成了 4 个包,但应用程序没有显示,我也没有收到任何错误。

但是,如果我将依赖项放在一个条目中,效果很好:

webpack.config.js

entry: {
    workshop: {
      import: "./wwwroot/component/WorkshopApp.tsx",
      dependOn: ["workshopVendor"],
    },
    workshopVendor: [
      "axios",
      "highcharts-react-official",
      "highcharts/highmaps",
    ],
  },

.cshtml:

<div id="workshop" data-id=@Model></div>
<script src="~/bundles/js/workshopVendor-bundle.js"></script>
<script src="~/bundles/js/workshop-bundle.js"></script>

这不是解决方案,因为我想要单独捆绑包中的依赖项,知道吗? 提前致谢!

不再建议将供应商包定义为单独的入口点。我认为您 运行 遇到了一些依赖关系图错误。 Webpack 应该能够使用 optimization.splitChunks 自动修复这个问题。这样的事情应该有效:

module.exports = {
  //...
  optimization: {
    splitChunks: {
      cacheGroups: {
        axios: {
          test: /[\/]node_modules[\/]axios[\/]/,
          name: 'axios',
          chunks: 'all',
        },
       'highcharts-react-official': {
          test: /[\/]node_modules[\/]highcharts-react-official[\/]/,
          name: 'highcharts-react-official',
          chunks: 'all',
        },
       'highcharts/highmaps': {
          test: /[\/]node_modules[\/]highcharts[\/]highmaps[\/]/,
          name: 'highcharts/highmaps',
          chunks: 'all',
        },
      },
    },
  },
};

Per the docs:

Tip

In webpack version < 4 it was common to add vendors as a separate entry point to compile it as a separate file (in combination with the CommonsChunkPlugin).

This is discouraged in webpack 4. Instead, the optimization.splitChunks option takes care of separating vendors and app modules and creating a separate file. Do not create an entry for vendors or other stuff that is not the starting point of execution.