CommonsChunkPlugin

2023-06-01 15:19 更新

?CommonsChunkPlugin? 是一項(xiàng)可選功能,它創(chuàng)建一個(gè)獨(dú)立的文件(稱為 chunk),其中包含多個(gè)入口點(diǎn)之間共享的公共模塊。

通過將公共模塊與捆綁包分開,生成的分塊文件可以在最初加載一次,并存儲(chǔ)在緩存中供以后使用。這導(dǎo)致頁面速度優(yōu)化,因?yàn)闉g覽器可以快速提供緩存中的共享代碼,而不是在訪問新頁面時(shí)被迫加載更大的包。

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

生成一個(gè)額外的塊,其中包含在入口點(diǎn)之間共享的公共模塊。

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

您必須在入口點(diǎn)之前加載生成的塊:

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

Explicit vendor chunk

將您的代碼拆分為供應(yīng)商和應(yīng)用程序。

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

使用代碼拆分,入口塊的多個(gè)子塊可以具有共同的依賴關(guān)系。為了防止重復(fù),可以將這些移到父級(jí)中。這會(huì)減小整體尺寸,但會(huì)對(duì)初始加載時(shí)間產(chǎn)生負(fù)面影響。如果預(yù)計(jì)用戶將需要下載許多兄弟塊,即入口塊的子塊,那么這應(yīng)該會(huì)改善整體加載時(shí)間。

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

與上面的類似,但不是將公共模塊移動(dòng)到父模塊(這會(huì)增加初始加載時(shí)間),而是使用一個(gè)新的異步加載的額外公共塊。當(dāng)下載附加塊時(shí),它會(huì)自動(dòng)并行下載。

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? 屬性傳遞給函數(shù)。此函數(shù)由 ?CommonsChunkPlugin? 調(diào)用,并使用 ?module? 和 ?count? 參數(shù)調(diào)用該函數(shù)。

?module? 參數(shù)表示您通過 ?name?/?names? 屬性提供的塊中的每個(gè)模塊。模塊具有 ?NormalModule? 的形狀,它具有兩個(gè)對(duì)于此用例特別有用的屬性:

  • ?module.context?: 存儲(chǔ)文件的目錄。

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

  • ?module.resource?: 正在處理的文件的名稱。

例如:?

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

count 參數(shù)表示模塊被使用了多少塊。

當(dāng)您希望對(duì) ?CommonsChunk? 算法如何確定模塊應(yīng)移動(dòng)到的位置進(jìn)行細(xì)粒度控制時(shí),此選項(xiàng)很有用。

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

如上所示,當(dāng)且僅當(dāng)函數(shù)內(nèi)部滿足所有條件時(shí),此示例才允許您將一個(gè)庫移動(dòng)到單獨(dú)的文件。

此概念可用于獲取隱式公共供應(yīng)商塊:

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 引導(dǎo)程序邏輯提取到單獨(dú)的文件中,請(qǐng)?jiān)谖炊x為條目的名稱上使用 ?CommonsChunkPlugin?。通常使用名稱 ?manifest?。有關(guān)詳細(xì)信息,請(qǐng)參閱緩存指南。

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

Combining implicit common vendor chunks and manifest file

由于 ?vendor? 和 ?manifest? chunk 使用不同的 ?minChunks? 定義,你需要調(diào)用插件兩次:

[
  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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)