webpack.optimize.CommonsChunkPlugin 詳解

#明確概念node

  • entry的每個入口文件都叫chunk (entry chunk)
  • 每一個入口文件異步加載也叫chunk(children chunk)
  • 經過commonChunkPlugin 抽離出來的也叫chunk(common chunk)

#使用場景jquery

  1. 多入口文件,須要抽出公告部分的時候。
  2. 單入口文件,可是由於路由異步加載對多個子chunk, 抽離子每一個children公共的部分。
  3. 把第三方依賴,理由node_modules下全部依賴抽離爲單獨的部分。
  4. 混合使用,既須要抽離第三方依賴,又須要抽離公共部分。

#實現部分 項目結構 webpack

image.png

// a.js
 import { common1 } from './common'
 import $ from 'jquery';
 console.log(common1, 'a')

  //b.js
  import { common1 } from './common'
  import $ from 'jquery';
  console.log(common1, 'b')

  //common.js
  export const common1 = 'common1'
  export const common2 = 'common2'
複製代碼

在不使用插件的前提下打包結果以下: git

image.png

case 1 把多入口entry抽離爲common.jsgithub

plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: "common",
      filename: "common.js"
    })
  ]
複製代碼

執行結果以下: web

image.png

case 2 從children chunk抽離 common.jsbash

// 單入口文件 main.js
const component1 = function(resolve) {
  return require(['./a'], resolve)
}
const component2 = function(resolve) {
  return require(['./b'], resolve)
}
console.log(component1, component2, $, 'a')
複製代碼

不使用commonChunk執行結果以下: 異步

image.png

//使用commonChunk 配置以下
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      children: true,
      async: 'children-async',
      name: ['main']
    })
  ]
複製代碼

// 執行結果以下 async

image.png

case 3 node_modules全部額三方依賴抽離爲vendor.js函數

//webpack 配置
...
  entry : {
    main: './src/main.js',
    vendor: ['jquery']
  }
...
...
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',  // 這裏是把入口文件全部公共組件都合併到 vendor模塊當中
      filename: '[name].js'
    })
...
複製代碼

執行結果若是下:

image.png

case 4 case 2和case 3混合使用 vendor.js是三方依賴提取,0.js是children公共部分提取

....
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name:  'vendor',
      filename: '[name].js'
    }),
    new webpack.optimize.CommonsChunkPlugin({
      children: true,
      async: 'children-async',
      name: ['main']
    })
  ]
....
複製代碼

執行結果以下:

image.png

github 源碼下載

#注意的幾點

  • name: 若是entry和CommonsChunkPlugin的 name 都有vendor 是把抽離的公共部分合併到vendor這個入口文件中。 若是 entry中沒有vendor, 是把入口文件抽離出來放到 vendor 中。
  • minChunks:既能夠是數字,也能夠是函數,還能夠是Infinity。 數字:模塊被多少個chunk公共引用才被抽取出來成爲commons chunk 函數:接受 (module, count) 兩個參數,返回一個布爾值,你能夠在函數內進行你規定好的邏輯來決定某個模塊是否提取 成爲commons chunk
    image.png
    Infinity:只有當入口文件(entry chunks) >= 3 才生效,用來在第三方庫中分離自定義的公共模塊
  • commonChunk 以後的common.js 還能夠繼續被抽離,只要從新new CommonsChunkPlugin中name:配置就好就能夠實現
  • 以上方法只使用與 webpack 4 如下版本
相關文章
相關標籤/搜索