有没有一种方法可以在Webpack 4中使用splitChunksPlugin来手动控制将哪些模块放入哪个输出包中?

时间:2019-04-15 21:09:50

标签: webpack webpack-4 webpack-splitchunks

我处于一种特殊的情况下,我需要将我的捆绑包拆分成单独的文件,但我无法奢侈地让文件总数或这些文件的名称随着应用程序的变化而变化增长并安装了新的依存关系,等等。

以下配置是错误的,但是我认为它可以最好地说明我正在尝试要完成的工作。我已经阅读了所有文档,但似乎找不到这些路线。

optimization: {
  splitChunks: {
    react: {
      test: /node_modules\/react/
    },
    vendor: {
      test: /node_modules\/(?!react)/
    },
    svgIcons: {
      test: /src\/js\/components\/icons/
    },
  }
}

目的是最终得到以下4个捆绑包:

react.bundle.js - Contains all react-related dependencies
vendor.bundle.js - Contains all other vendor files from node modules
svgIcons.bundle.js - Contains a group of app component files that match my test
bundle.js - The default bundle containing everything else.

有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

经过进一步的挖掘,我终于弄清楚了。本质上,这就是您需要的:

首先,在output对象中……

output: {
  filename: "[name].js"
}

您需要使用[name]变量,否则您的分发包将不会选择正确的名称。

接下来,在optimization对象中……

optimization: {
  splitChunks: {
    cacheGroups: {
      react: {
        chunks: 'initial',
        name: 'react',
        test: /node_modules\/react/,
        enforce: true,
      },
      vendor: {
        chunks: 'initial',
        name: 'vendor',
        test: /node_modules\/(?!react)/,
        enforce: true,
      },
      icons: {
        chunks: 'initial',
        name: 'icons',
        test: /src\/js\/components\/icons/,
        enforce: true,
      },
    },
  },
},

产生以下捆绑包:

react.js
vendor.js
icons.js
bundle.js