CommonsChunkPlugin

2023-06-01 15:19 更新

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

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

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

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

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

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

  • ?module.context?: 存儲文件的目錄。

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

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

例如:?

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

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

當您希望對 ?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;
  },
});

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

此概念可用于獲取隱式公共供應商塊:

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? 定義,你需要調(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)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號