栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

详解webpack 打包文件体积过大解决方案(code splitting)

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解webpack 打包文件体积过大解决方案(code splitting)

优化对比 :

  未优化前:index.html引入一个main.js文件,体积2M以上。

  优化后入:index.html引入main.js、commons.js、charts.js、other.js。以达到将main.js平分目的。每个文件控制300k以内.(如果高兴100k也没问题)

用到的一堆库及工具:

vue、webpack、babel、highcharts、echarts、jquery、html2canvas******此去省略若干m代码

问题:

  开发环境用webpack后发现单个js文件5m。

  生产环境借助vue-cli的webpack配置,减少到2m。

解决方案:

  搜索各种解决方案:require.ensure、require依赖、多entry、commonsChunkPlugin****此去省力若干方案

网络类似下边这种上解决方案太多了,但是都达不到预期效果

entry:{ 
 main:'xxx.js',
  chunks:['c1', 'c2'],
  commons:['jquery', 'highcharts', 'echarts','d3', 'xxxxx.js']  
}

 

plugins:{
new commonsChunkPlugin({
name:'commons',
minChunks:2
})  
}

最优解决方案:

entry:{ 
 main:'xxx.js'
}
 
plugins:{
 new commonsChunkPlugin({
 name:'commons',
 minChunks:function(module){
  // 下边return参考的vue-cli配置
  // any required modules inside node_modules are extracted to vendor
  return (
   module.resource &&
   /.js$/.test(module.resource) &&
   module.resource.indexOf(
   path.join(__dirname, '../node_modules')
   ) === 0
  )
 }
}) ,
// 以下才是关键
new commonsChunkPlugin({
 name:'charts',
 chunks:['commons'] 
 minChunks:function(module){
  return (
   module.resource &&
   /.js$/.test(module.resource) &&
   module.resource.indexOf(
   path.join(__dirname, '../node_modules')
   ) === 0 && ['jquery.js', 'highcharts.js','echarts'].indexOf( module.resource.substr(module.resource.lastIndexOf('/')+1).toLowerCase() ) != -1
  )
 }
}) // 如果愿意,可以再new 一个commonsChunkPlugin
 
}

以上代码打包出来的结果:main.js 、commons.js、charts.js 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/81557.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号