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  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM