Vue+Webpack之 代碼及打包優化

本文重點介紹Vue單頁面應用的優化手段:

  • 異步加載
  • 面切換時加loading特效
  • 點擊延遲
  • inline manifest
  • 邏輯代碼優化
  • 依賴包體積優化
  • cdn引用

Vue代碼優化

異步加載

所謂的異步加載組件,其實就是組件懶加載。可以理解爲:當我需要使用組件的時候才進行加載。主要包含兩部分:路由配置和子組件的調用。
所以在router文件夾下 index.js 做如下配置
QQ--20190830170123

組件優化

由於是後臺項目,所以選擇element-ui框架進行後臺系統搭建,所以對這個進行優化也可以減小體積,提高速度和減少加載時間,提高用戶體驗。

全局使用
全局引入和使用
import elementUI from 'element-ui'
Vue.use(elementUI)
這種方法對於只用少量element-ui組件的情況來說,很多組件都是多餘的,會無形中加大加載時間和項目打包後的體積,所以使用下面這種按需引入的方法可以有效解決這個問題。

按需引入

// 按需引入

import {
  Form,
  Button,
  Table,
} from 'element-ui'

// 按需使用
Vue.use(Form)
Vue.use(Button)
Vue.use(Table)
複製代碼
還要一些加載和消息提示等的組件,以下寫法:

// 按需引入
import {
  Loading,
  Message,
  MessageBox,
  Notification,
} from 'element-ui'
 
// 按需使用
Vue.use(Loading.directive)
// 掛載到vue實例上面
Vue.prototype.$loading = Loading.service
Vue.prototype.$msgbox = MessageBox
Vue.prototype.$confirm = MessageBox.confirm
Vue.prototype.$alert = MessageBox.alert
Vue.prototype.$prompt = MessageBox.prompt
Vue.prototype.$message = Message
Vue.prototype.$notify = Notification,
使用通知組件可以,這麼調用也可以,Notification(options),或者Notification.success(options)。

  

頁面切換時加loading特效

頁面的響應、渲染速度的影響原因多種多樣。爲了解決用戶在首次進入應用或者頁面切換的時等待的白屏時間較長時,可以使用vue-router提供的beforeEach()和afterEach()方法。所以使用loading進度條是一種比較明智的做法。使用nprogress。API可參考官方文檔,使用方法如下(假設已經安裝好了nprogress):

在router.js中使用import引入nprogress以及它的樣式表,配置ngprocess。並在路由配置完成後,調用beforeEach() 和 afterEach方法

//路由配置前
NProgress.configure({ showSpinner: false })
 
//此處爲路由配置列表,可參考上面的異步加載方式進行編寫
//路由配置後
router.beforeEach(function (to, from, next) {
  NProgress.start() //開始loading
  const toIndex = history.getItem(to.path)
  const fromIndex = history.getItem(from.path)
 
  if (toIndex) {
    if (!fromIndex || parseInt(toIndex, 10) > parseInt(fromIndex, 10) || (toIndex === '0' && fromIndex === '0')) {
      store.commit('UPDATE_DIRECTION', {direction: 'forward'})
    } else {
      // 判斷是否是ios左滑返回
      if (!isPush && (Date.now() - endTime) < 377) {
        store.commit('UPDATE_DIRECTION', {direction: ''})
      } else {
        store.commit('UPDATE_DIRECTION', { direction: 'reverse' })
      }
    }
  } else {
    ++historyCount
    history.setItem('count', historyCount)
    to.path !== '/' && history.setItem(to.path, historyCount)
    store.commit('UPDATE_DIRECTION', {direction: 'forward'})
  }
 
  if (/\/http/.test(to.path)) {
    let url = to.path.split('http')[1]
    window.location.href = `http${url}`
  } else {
    next()
  }
})
 
router.afterEach(function (to) {
  NProgress.done() //loading結束
})

  

點擊延遲

安裝fastclick後,在main.js中引入即可:

import FastClick from 'fastclick'
FastClick.attach(document.body)

inline manifest

manifest文件時路徑配置和異步組件名字列表,這麼做可以減少一個http請求。具體做法爲,先在入口頁面index.html中的head的最後一行加入代碼

<%=htmlWebpackPlugin.files.webpackManifest%>

最後在webpack的公共配置文件(我的是webpack.base.conf.js)的vux-loader配置的 plugins 列表中加入inline-manifest插件:

module.exports = vuxLoader.merge(webpackConfig, {
  plugins: ['inline-manifest', 'vux-ui', 'progress-bar', 'duplicate-style']
})

邏輯代碼優化

這部分的建議就是:①每個vue文件儘可能小(多使用組件,加強可複用性);②vue指令中的v-show和v-if的使用:v-if耗性能更多,所以頻繁切換的使用 v-show,不頻繁切換的使用 v-if;③vue指令中的v-for搭配:key使用,確保唯一性;④樣式表css務必加scoped以防止干擾————————————————

webpack配置優化

依賴包體積優化

衆所周知,日常開發過程中,前端這塊早就已經開始進行工程化和組件化開發了,所以免不了下載各種node包,使得打包後的體積也是非常的龐大,下面使用webpack的一個配置外部擴展就可以解決這類問題。

Gzip壓縮和sourceMap優化

這個也是壓縮文件的一個方法,線上服務器的nginx也開啓gzip功能更好;取消資源地圖,可以有效保護源碼。

在webpack的build文件中,開啓Gzip壓縮功能和禁用資源地圖。

module.exports = {
  // ...
  build: {
    productionSourceMap: false,
    productionGzip: true,
  }
}

這樣做的話,打包以後就不會再有sourceMap文件了,也會多了幾個以.js.gz後綴名的文件

cdn引用

方法爲:在webpack的公共配置文件(一般爲webpack.base.conf.js)的resolve下有extensions選項。數組中加入不需要打包的組件,並且在入口的html中使用cdn的方式引入即可,此時會發現打包出來的vender包會變小很多.

具體步驟

以 vue, vue-router,element-ui爲例

步驟1 index.html cdn引入框架

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>demo-vue-project</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/element-ui/2.0.8/theme-chalk/index.css">
  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
    <script src="https://cdn.bootcss.com/vue/2.5.13/vue.min.js"></script>
    <script src="https://cdn.bootcss.com/vue-router/2.7.0/vue-router.min.js"></script>
    <script src="https://cdn.bootcss.com/element-ui/2.0.7/index.js"></script>
  </body>
</html>

  

步驟2 修改 build/webpack.base.conf.js

module.exports = {
  ...
  externals: {
    'vue': 'Vue',
    'vue-router': 'VueRouter',
    'element-ui': 'ELEMENT'
  },
  ...
}

  

步驟3 修改框架註冊方式
修改 src/router/index.js

// import Vue from 'vue'
import VueRouter from 'vue-router'
// 註釋掉
// Vue.use(VueRouter)
...

  

修改 src/main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import ELEMENT from 'element-ui'
// import 'element-ui/lib/theme-chalk/index.css'

Vue.config.productionTip = false

Vue.use(ELEMENT)
Vue.prototype.$http = axios

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  template: '<App/>',
  components: { App }
})

  

總結

至此 vue-cli2.0中的打包配置,也有一些瞭解了。個人吐槽下webpack是真的複雜。觀望和期待 vue-cli3.0+webpack4.0能來帶不一樣的體驗。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章