webpack.optimize.CommonsChunkPlugin 详解

#明确概念

  • entry的每一个入口文件都叫chunk (entry chunk)
  • 每个入口文件异步加载也叫chunk(children chunk)
  • 通过commonChunkPlugin 抽离出来的也叫chunk(common chunk)

#使用场景

  1. 多入口文件,需要抽出公告部分的时候。
  2. 单入口文件,但是因为路由异步加载对多个子chunk, 抽离子每个children公共的部分。
  3. 把第三方依赖,理由node_modules下所有依赖抽离为单独的部分。
  4. 混合使用,既需要抽离第三方依赖,又需要抽离公共部分。

#实现部分 项目结构

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'
复制代码

在不使用插件的前提下打包结果如下:

image.png

case 1 把多入口entry抽离为common.js

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: "common",
      filename: "common.js"
    })
  ]
复制代码

执行结果如下:

image.png

case 2 从children chunk抽离 common.js

// 单入口文件 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']
    })
  ]
复制代码

// 执行结果如下

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 以下版本

猜你喜欢

转载自juejin.im/post/5c2205e15188257507558c5a