前端架構師必備之Vue項目打包優化

前端架構師必備之Vue項目打包優化

前幾天聽老師講過前端架構師必備之Vue項目打包優化的課之後,有感而發利用空閒時間寫了一下。

大佬路過請留步指導一下,

使用vue-cli部署生產包時,發現資源包很大,打包後的vendor.js達到了1.4M,這已經很大了,而且會影響到首屏加載。那麼,怎麼優化呢?

1.組件按需加載

這是首先可以優化的點。如果頻繁使用了第三方組件/UI庫,如我的項目中經常同時使用了 element-ui, mint-ui,echarts等組件庫,如果全部引入,項目體積非常大,這時可以按需引入組件。

示例如下:

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"
}
```

然後引入部分組件,這樣一來,就不需要引入樣式了,插件會幫我們處理。

?

// main.js
import 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的移動端組件,所以它的使用和引入幾乎和element-ui一樣。

首先,安裝 babel-plugin-component:

npm install babel-plugin-component -D

然後,將.babelrc 修改為:

{
"presets": [
["es2015", { "modules": false }]
],
"plugins": [["component", [
{
"libraryName": "mint-ui",
"style": true

}
]]]
}

然後引入部分組件

// main.js
import 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不能同時在.babelrc中進行插件設置,這種情況下,依然可以按需引入,但是不要在.babelrc中配置,在引入的地方同時引入css即可。

1.3 echarts

首先安裝babel-plugin-equire

npm i babel-plugin-equire -D

然後,在.babelrc文件中添加該插件

{

 "plugins": [
// other plugins
...

"equire"
]
}

創建一個js文件

// echarts.js
// eslint-disable-next-line
const echarts = equire([
'tooltip',
'candlestick',
'bar',
'line',
'axisPointer',
'legend',
'grid'
])
export default echarts

// 業務組件,引入echarts

import echarts from '@/assets/lib/echarts'

// 使用與以前一樣

按需加載echarts

解決vue-cli首屏加載慢的問題

2.路由懶加載

這裡需要一個插件

vue-router官方推薦syntax-dynamic-import插件,不過它要求同時安裝@bable/core^7.0.0,如果你安裝了babel-core6,是會有版本衝突的。我的做法如下

npm install babel-plugin-syntax-dynamic-import --save-dev(^6.18.0)
// router.js
const login = () => import('@/components/login')
const router = new VueRouter({
routes: [
{ path: '/login', component: login }
]
})

還有一種魔法註釋用法

有時候我們想把某個路由下的所有組件都打包在同個異步塊 (chunk) 中。只需要使用 命名 chunk,一個特殊的註釋語法來提供 chunk name (需要 Webpack > 2.4)。

const Foo = () => import(/* webpackChunkName: "group-foo" */ './Foo.vue')

3.異步組件

如果組件在頁面加載時不需要,只在調用時用到,這時可以使用異步組件的寫法。僅僅是引入和組件註冊寫法不同

// template


// script
components: {
test: () => import('./test') // 將組件異步引入,告訴webpack,將該部分代碼分割打包
},
methods:{
clickTest () {
this.showTest = !this.showTest
}
}

4.圖片的壓縮合並

無損壓縮圖片:https://www.jb51.net/softs/605425.html

如有可能,將圖片製作成精靈圖

5.CDN加速

在index.html中引入cdn資源






-->


分享到:


相關文章: