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 如下版本
相关文章
相关标签/搜索