webpack 打包檔案體積過大解決方案(code splitting)

來源:互聯網
上載者:User

標籤:highchart   split   ensure   ret   com   jquer   back   r.js   extract   

最佳化對比 :

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

 

webpack 打包檔案體積過大解決方案(code splitting)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.