webpack之SplitChunksPlugin

使用 SplitChunksPlugin 提取 chunks 中的公共代码,生成新的 chunk

  • chunk 的三种情况

    • 项目入口 entry
    • 通过import()动态引入的代码
    • 通过 splitChunks 拆分出来的代码
  • splitChunks 默认配置(部分)

module.exports = {
  //...
  optimization: {
    splitChunks: {
      chunks: 'async', // chunk 类别, async 查动态导入模块(import),all 查全部,initial - 非动态
      minSize: 20000, // 最小大小
      minChunks: 1, // 最小引用数
      automaticNameDelimiter: '~', // 生成 chunk 文件名中的连接符
      cacheGroups: { // 继承或重写 splitChunks.*
        defaultVendors: { // cacheGroups 名
          test: /[\\/]node_modules[\\/]/, // 文件过滤,省略查询所有模块
          priority: -10, // 权重
        },
        default: {	 // 
          minChunks: 2,
          priority: -20,
        }
      }
    }
  }
};

多项目入口提取 公共chunk

// a.js
import './helpers.js'

// b.js
import './helpers.js'

// helpers.js
console.log('helpers')
module.exports = {
	// ...
  entry: {
    a: path.resolve(__dirname, './src/a.js'),
    b: path.resolve(__dirname, './src/b.js')
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name]_[chunkhash:8].js'
  },
  optimization: {
    splitChunks: {
      cacheGroups: { // 继承或重写 splitChunks.*
        default: {
          name: 'common', // chunk 名称
          chunks: 'initial', // chunk 类别
          minSize: 0, // 最小大小
          minChunks: 2,
          priority: -20,
        }
      }
    }
  }
}

在这里插入图片描述

node_modules 提取 chunk

// a.js
import './helpers.js'

// helpers.js
console.log('helpers')


import _ from 'lodash'

console.log(_.join(['Hello', 'webpack'], ' '));
module.exports = {
  entry: {
    a: path.resolve(__dirname, './src/a.js'),
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name]_[chunkhash:8].js'
  },
  optimization: {
    splitChunks: {
      cacheGroups: { // 继承或重写 splitChunks.*
        defaultVendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
          chunks: 'initial', // chunk 类别
          name: 'vendors'
        },
      }
    }
  }
}

在这里插入图片描述

开箱即用的 splitChunks (使用默认值)

  • 动态导入,使用 lodash 依赖,生成两个 chunk
// a.js
import(/* webpackChunkName: "helpers" */'./helpers')

// helpers.js
console.log('helpers')
import _ from 'lodash'

console.log(_.join(['Hello', 'webpack'], ' '));

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值