使用vue-cli部署生產(chǎn)包時(shí),發(fā)現(xiàn)資源包很大,打包后的vendor.js達(dá)到了1.4M,這已經(jīng)很大了,而且會(huì)影響到首屏加載。那么,怎么優(yōu)化呢?
1.組件按需加載
這是首先可以優(yōu)化的點(diǎn)。如果頻繁使用了第三方組件/UI庫(kù),如我的項(xiàng)目中經(jīng)常同時(shí)使用了 element-ui, mint-ui,echarts等組件庫(kù),如果全部引入,項(xiàng)目體積非常大,這時(shí)可以按需引入組件。
示例如下:
1.1 element-ui
首先,安裝 babel-plugin-component:
npm install babel-plugin-component -D
然后,將.babelrc 修改為:
{ "presets": [["es2015", { "modules": false }]], "plugins": [ [ "component", { "libraryName": "element-ui", "styleLibraryName": "theme-chalk" } ] ]}然后引入部分組件,這樣一來(lái),就不需要引入樣式了,插件會(huì)幫我們處理。
// main.jsimport Vue from 'vue'import { Dialog, Loading } from 'element-ui'Vue.use(Dialog)Vue.use(Loading.directive)Vue.prototype.$loading = Loading.service// 然后正常使用組件1.2 mint-ui
由于mint-ui是element-ui的移動(dòng)端組件,所以它的使用和引入幾乎和element-ui一樣。
首先,安裝 babel-plugin-component:
npm install babel-plugin-component -D
然后,將.babelrc 修改為:
{ "presets": [ ["es2015", { "modules": false }] ], "plugins": [["component", [ { "libraryName": "mint-ui", "style": true } ]]]}然后引入部分組件
// main.jsimport Vue from 'vue'import { Toast, MessageBox } from 'element-ui'Vue.use(Dialog)Vue.use(Loading.directive)Vue.prototype.$loading = Loading.service// 然后正常使用組件注意,element-ui和mint-ui不能同時(shí)在.babelrc中進(jìn)行插件設(shè)置,這種情況下,依然可以按需引入,但是不要在.babelrc中配置,在引入的地方同時(shí)引入css即可。
1.3 echarts
首先安裝babel-plugin-equire
npm i babel-plugin-equire -D
然后,在.babelrc文件中添加該插件
{ "plugins": [ // other plugins ... "equire" ]}創(chuàng)建一個(gè)js文件
// echarts.js// eslint-disable-next-lineconst echarts = equire([ 'tooltip', 'candlestick', 'bar', 'line', 'axisPointer', 'legend', 'grid'])export default echarts// 業(yè)務(wù)組件,引入echartsimport echarts from '@/assets/lib/echarts'// 使用與以前一樣
按需加載echarts
解決vue-cli首屏加載慢的問(wèn)題
2.路由懶加載
這里需要一個(gè)插件
vue-router官方推薦syntax-dynamic-import插件,不過(guò)它要求同時(shí)安裝@bable/core^7.0.0,如果你安裝了babel-core6,是會(huì)有版本沖突的。我的做法如下
新聞熱點(diǎn)
疑難解答
圖片精選