javascript - 疑问: webpack CommonsChunkPlugin 的 minChunks
ringa_lee
ringa_lee 2017-04-11 12:44:04
0
0
371

问题描述

  1. minChunks = Infinity 的使用场景是哪些?

  2. minChunks 的默认值是什么

我的理解

官方文档描述:

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 just 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)

注意其中的两句:

  • Passing Infinity just creates the commons chunk, but moves no modules into it

  • Defaults to the number of chunks

官方文档中还有一句:

minChunks: Infinity,
with more entries, this ensures that no other module goes into the vendor chunk

我的理解是:

  • minChunks = Infinity 仅仅在 source entry chunks 的数量 >= 3 的时候才起作用

  • minChunks 的默认值应该为 source entry chunks 的数量

我的测试

webpack 配置:

const path = require('path')
const webpack = require('webpack')

module.exports = {
  entry: {
    vendor: ['vendor-module1', 'vendor-module2'],
    app: ['main'],
    'other-entry': ['main2']
  },
  output: {
    path: path.resolve(__dirname, './dist'),
    filename: '[name].js'
  },
  resolve: {
    modules: [path.resolve(__dirname, './src'), 'node_modules']
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: Infinity
      // minChunks: 2
      // minChunks: 3
    })
  ]
}

模块依赖关系如图:

针对每一种 minChunks 的值, webpack 编译打包的结果不同, 总结如下:

  • minChunks = default 时打包情况:

    • app.js

      • main

      • module2

    • vendor.js

      • webpack runtime / webpackBootstrap

      • vendor-module1

      • vendor-module2

      • module1

      • module3

    • other-entry.js

      • main2

      • other-module

  • minChunks = 2 时打包情况:
     同 default

  • minChunks = 3 时打包情况:

    • app.js

      • module3

      • module1

      • main

      • module2

    • vendor.js

      • webpack runtime / webpackBootstrap

      • vendor-module1

      • vendor-module2

    • other-entry.js

      • module3

      • module1

      • main2

      • other-module

  • minChunks = Infinity 时打包情况:
     同 minChunks = 3 (number of all source entry chunks)

我的结论

  1. minChunks 默认值为 2 (最小值), 不是官方文档所描述的 "Defaults to the number of chunks"

  2. 在 minChunks = 2 (或默认值) 时, module1 和 module3 由于被 app chunk 和 other-entry chunk 共同引用, 所以被提取到了 vendor (commons chunk) 中了, 而在分离 vendor 的优化方案中, 我们并不想得到这种结果, 我们想让产出的 vendor chunk 只包含第三方类库就好, 即使某个应用自身模块被再多的(非 vendor) entry chunk 引用, 我也不想要将这个应用自身模块提取到 vendor chunk 中, 这种情况下就需要设置 minChunks 为 Infinity

  3. 根据梳理的打包结果看, 将 minChunks 设置为 Infinity 或 设置为 "所有的 entry chunk 数量 (示例中为3)", 其效果是相同的.

欢迎理解 CommonsChunkPlugin 的同学指点一二. 感谢.

ringa_lee
ringa_lee

ringa_lee

全員に返信(0)
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!