優化對比 :
未優化前: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 }
相信看了本文案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
推薦閱讀:
JS對圖片進行黑白化設置
vue select組件開啟與禁用方法詳解
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com