欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2021-03-06 10:09:58|栏目:JavaScript代码|点击:

优化对比 :

  未优化前: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 

上一篇:js判断当前页面在移动设备还是在PC端中打开

栏    目:JavaScript代码

下一篇:不错的文字特效,逐字变色效果

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

本文地址:http://www.codeinn.net/misctech/75082.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有