轉自https://mp.weixin.qq.com/s/3kGPcQ7xduLqAEAaWRJbgw
一、是什么
Tree shaking
是一種通過清除多余代碼方式來優化項目打包體積的技術,專業術語叫 Dead code elimination
簡單來講,就是在保持代碼運行結果不變的前提下,去除無用的代碼
如果把代碼打包比作制作蛋糕,傳統的方式是把雞蛋(帶殼)全部丟進去攪拌,然后放入烤箱,最后把(沒有用的)蛋殼全部挑選並剔除出去
而treeshaking
則是一開始就把有用的蛋白蛋黃(import)放入攪拌,最后直接作出蛋糕
也就是說 ,tree shaking
其實是找出使用的代碼
在Vue2
中,無論我們使用什么功能,它們最終都會出現在生產代碼中。主要原因是Vue實例在項目中是單例的,捆綁程序無法檢測到該對象的哪些屬性在代碼中被使用到
import Vue from 'vue'
Vue.nextTick(() => {})
而Vue3
源碼引入tree shaking
特性,將全局 API 進行分塊。如果你不使用其某些功能,它們將不會包含在你的基礎包中
import { nextTick, observable } from 'vue'
nextTick(() => {})
二、如何做
Tree shaking
是基於ES6
模板語法(import
與exports
),主要是借助ES6
模塊的靜態編譯思想,在編譯時就能確定模塊的依賴關系,以及輸入和輸出的變量
Tree shaking
無非就是做了兩件事:
- 編譯階段利用
ES6 Module
判斷哪些模塊已經加載 - 判斷那些模塊和變量未被使用或者引用,進而刪除對應代碼
下面就來舉個例子:
通過腳手架vue-cli
安裝Vue2
與Vue3
項目
vue create vue-demo
Vue2 項目
組件中使用data
屬性
<script> export default { data: () => ({ count: 1, }), }; </script>
對項目進行打包,體積如下
為組件設置其他屬性(compted
、watch
)
export default { data: () => ({ question:"", count: 1, }), computed: { double: function () { return this.count * 2; }, }, watch: { question: function (newQuestion, oldQuestion) { this.answer = 'xxxx' } };
再一次打包,發現打包出來的體積並沒有變化
Vue3 項目
組件中簡單使用
import { reactive, defineComponent } from "vue"; export default defineComponent({ setup() { const state = reactive({ count: 1, }); return { state, }; }, });
將項目進行打包
在組件中引入computed
和watch
import { reactive, defineComponent, computed, watch } from "vue"; export default defineComponent({ setup() { const state = reactive({ count: 1, }); const double = computed(() => { return state.count * 2; }); watch( () => state.count, (count, preCount) => { console.log(count); console.log(preCount); } ); return { state, double, }; }, });
再次對項目進行打包,可以看到在引入computer
和watch
之后,項目整體體積變大了
三、作用
通過Tree shaking
,Vue3
給我們帶來的好處是:
- 減少程序體積(更小)
- 減少程序執行時間(更快)
- 便於將來對程序架構進行優化(更友好)