CommonsChunkPlugin

CommonsChunkPlugin 是一项选择加入功能,它创建一个单独的文件(称为块),其中包含在多个入口点之间共享的公共模块。

通过将公共模块与包分离,可以一次性加载生成的块文件,并将其存储在缓存中以供以后使用。这将优化页面速度,因为浏览器可以快速从缓存中提供共享代码,而不必在每次访问新页面时加载更大的包。

new webpack.optimize.CommonsChunkPlugin(options);

选项

{
  name: string, // or
  names: string[],
  // The chunk name of the commons chunk. An existing chunk can be selected by passing a name of an existing chunk.
  // If an array of strings is passed this is equal to invoking the plugin multiple times for each chunk name.
  // If omitted and `options.async` or `options.children` is set all chunks are used, otherwise `options.filename`
  // is used as chunk name.
  // When using `options.async` to create common chunks from other async chunks you must specify an entry-point
  // chunk name here instead of omitting the `option.name`.

  filename: string,
  // The filename template for the commons chunk. Can contain the same placeholders as `output.filename`.
  // If omitted the original filename is not modified (usually `output.filename` or `output.chunkFilename`).
  // This option is not permitted if you're using `options.async` as well, see below for more details.

  minChunks: number|Infinity|function(module, count) => boolean,
  // The minimum number of chunks which need to contain a module before it's moved into the commons chunk.
  // The number must be greater than or equal 2 and lower than or equal to the number of chunks.
  // Passing `Infinity` creates the commons chunk, but moves no modules into it.
  // By providing a `function` you can add custom logic. (Defaults to the number of chunks)

  chunks: string[],
  // Select the source chunks by chunk names. The chunk must be a child of the commons chunk.
  // If omitted all entry chunks are selected.

  children: boolean,
  // If `true` all children of the commons chunk are selected

  deepChildren: boolean,
  // If `true` all descendants of the commons chunk are selected

  async: boolean|string,
  // If `true` a new async commons chunk is created as child of `options.name` and sibling of `options.chunks`.
  // It is loaded in parallel with `options.chunks`.
  // Instead of using `option.filename`, it is possible to change the name of the output file by providing
  // the desired string here instead of `true`.

  minSize: number,
  // Minimum size of all common module before a commons chunk is created.
}

示例

针对入口的公共块

生成一个额外的块,其中包含在入口点之间共享的公共模块。

new webpack.optimize.CommonsChunkPlugin({
  name: 'commons',
  // (the commons chunk name)

  filename: 'commons.js',
  // (the filename of the commons chunk)

  // minChunks: 3,
  // (Modules must be shared between 3 entries)

  // chunks: ["pageA", "pageB"],
  // (Only use these entries)
});

必须在入口点之前加载生成的块

<script src="commons.js" charset="utf-8"></script>
<script src="entry.bundle.js" charset="utf-8"></script>

显式供应商块

将代码拆分为供应商和应用程序。

module.exports = {
  //...
  entry: {
    vendor: ['jquery', 'other-lib'],
    app: './entry',
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      // filename: "vendor.js"
      // (Give the chunk a different name)

      minChunks: Infinity,
      // (with more entries, this ensures that no other module
      //  goes into the vendor chunk)
    }),
  ],
};
<script src="vendor.js" charset="utf-8"></script>
<script src="app.js" charset="utf-8"></script>

将公共模块移入父块

使用 代码拆分 时,入口块的多个子块可能具有公共依赖项。为了防止重复,可以将这些依赖项移入父块。这会减小整体大小,但会对初始加载时间产生负面影响。如果预计用户需要下载许多同级块(即入口块的子块),那么这将总体上改善加载时间。

new webpack.optimize.CommonsChunkPlugin({
  // names: ["app", "subPageA"]
  // (choose the chunks, or omit for all chunks)

  children: true,
  // (select all children of chosen chunks)

  // minChunks: 3,
  // (3 children must share the module before it's moved)
});

额外的异步公共块

与上述类似,但不是将公共模块移入父级(这会增加初始加载时间),而是使用一个新的异步加载的附加公共块。当附加块下载时,它会自动并行下载。

new webpack.optimize.CommonsChunkPlugin({
  name: 'app',
  // or
  names: ['app', 'subPageA'],
  // the name or list of names must match the name or names
  // of the entry points that create the async chunks

  children: true,
  // (use all children of the chunk)

  async: true,
  // (create an async commons chunk)

  minChunks: 3,
  // (3 children must share the module before it's separated)
});

minChunks 属性传递给函数

您还可以将 minChunks 属性传递给函数。此函数由 CommonsChunkPlugin 调用,并使用 modulecount 参数调用该函数。

module 参数表示您通过 name/names 属性提供的块中的每个模块。module 具有 NormalModule 的形状,它具有两个对此用例特别有用的属性

  • module.context:存储文件的目录。例如:'/my_project/node_modules/example-dependency'
  • module.resource:正在处理的文件的名称。例如:'/my_project/node_modules/example-dependency/index.js'

count 参数表示 module 在其中使用的块数。

当您希望对 CommonsChunk 算法如何确定将模块移至何处进行细粒度控制时,此选项非常有用。

new webpack.optimize.CommonsChunkPlugin({
  name: 'my-single-lib-chunk',
  filename: 'my-single-lib-chunk.js',
  minChunks: function (module, count) {
    // If module has a path, and inside of the path exists the name "somelib",
    // and it is used in 3 separate chunks/entries, then break it out into
    // a separate chunk with chunk keyname "my-single-lib-chunk", and filename "my-single-lib-chunk.js"
    return module.resource && /somelib/.test(module.resource) && count === 3;
  },
});

如上所示,此示例允许您仅当函数内满足所有条件时,才将一个 lib 移至单独的文件。

此概念可用于获取隐式公共供应商块

new webpack.optimize.CommonsChunkPlugin({
  name: 'vendor',
  minChunks: function (module) {
    // this assumes your vendor imports exist in the node_modules directory
    return module.context && module.context.includes('node_modules');
  },
});

清单文件

要将 webpack 引导逻辑提取到单独的文件中,请对未定义为 entryname 使用 CommonsChunkPlugin。通常使用名称 manifest。有关详细信息,请参阅 缓存指南

new webpack.optimize.CommonsChunkPlugin({
  name: 'manifest',
  minChunks: Infinity,
});

组合隐式公共供应商块和清单文件

由于 vendormanifest 块对 minChunks 使用不同的定义,因此您需要调用插件两次

[
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor',
    minChunks: function (module) {
      return module.context && module.context.includes('node_modules');
    },
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'manifest',
    minChunks: Infinity,
  }),
];

更多示例

9 位贡献者

bebrawsimon04christopher4liskevinzwhuangjdbevanjeremenichellibyzykmadhavarshneysnitin315