CommonsChunkPlugin

2023-06-01 15:19 更新

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

通过将公共模块与捆绑包分开,生成的分块文件可以在最初加载一次,并存储在缓存中供以后使用。这导致页面速度优化,因为浏览器可以快速提供缓存中的共享代码,而不是在访问新页面时被迫加载更大的包。

new webpack.optimize.CommonsChunkPlugin(options);

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.
}

Examples

Commons chunk for entries

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

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>

Explicit vendor chunk

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

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>

Move common modules into the parent chunk

使用代码拆分,入口块的多个子块可以具有共同的依赖关系。为了防止重复,可以将这些移到父级中。这会减小整体尺寸,但会对初始加载时间产生负面影响。如果预计用户将需要下载许多兄弟块,即入口块的子块,那么这应该会改善整体加载时间。

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)
});

Extra async commons chunk

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

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)
});

Passing the minChunks property a function

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

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

  • module.context​: 存储文件的目录。

例如: ​'/my_project/node_modules/example-dependency'

  • module.resource​: 正在处理的文件的名称。

例如:​

'/my_project/node_modules/example-dependency/index.js'

count 参数表示模块被使用了多少块。

当您希望对 ​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;
  },
});

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

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

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');
  },
});

Manifest file

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

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

Combining implicit common vendor chunks and manifest file

由于 ​vendor​ 和 ​manifest​ chunk 使用不同的 ​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,
  }),
];

More Examples


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号