machao07 / interview-questions

前端技术栈相关面试知识点( Vue、React、Typescript、JavaScript...),喜欢请点start

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

vue3.0 中Treeshaking特性

machao07 opened this issue · comments

1、是什么

Tree shaking 是一种通过清除多余代码方式来优化项目打包体积的技术

Vue2

import Vue from 'vue'
 
Vue.nextTick(() => {})

Vue3

源码引入tree shaking特性,将全局 API 进行分

import { nextTick, observable } from 'vue'
 
nextTick(() => {})

2、 如何做

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'
        }
};

为项目打包

两次打包出来的体积并没有变化

image

vue3项目

初始组件

import { reactive, defineComponent } from "vue";
export default defineComponent({
  setup() {
    const state = reactive({
      count: 1,
    });
    return {
      state,
    };
  },
});

项目打包

image

在组件中引入 computed 和 watch

import { reactive, defineComponent, computed, watch } from "vue";
// ...

再次对项目进行打包,可以看到在引入computer和watch之后,项目整体体积变大了

image

3、总结

  • 减少程序体积(更小)
  • 减少程序执行时间(更快)
  • 便于将来对程序架构进行优化(更友好)