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

如上所見,此範例允許您僅當函式內的所有條件都符合時,才能將一個函式庫移至個別檔案。

此概念可用於取得隱含的常見供應商區塊

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