vue3快速入门-Tree shaking

本系列文章合集click me

本系列文章源码click me



Tree shaking是什么

Tree shaking 是一种通过清除多余代码dead-code方式来优化项目打包体积的技术, 也就是找出使用的代码。
Tree shaking 是基于ES6模板语法 importexport,主要是借助ES6模块的静态编译思想,在编译时就能确定模块的依赖关系,以及输入和输出的变量

Vue2.x使用全局方法

Vue 2.x 中,我们使用全局 API (如:nextTick) 是不需要我们手动去导入的。如下:

import Vue from 'vue'

Vue.nextTick(() => {})

也就是说,Vue全局API不是通过ES2015模块系统导入的,结合Tree shaking介绍,就可以知道在Vue2.x中,就算我们的代码没有使用到全局API,在项目打包的时候,这些全局API相关的dead-code依然会被一同打包进来,这样就导致了项目存在太多的无用代码。所以,Vue3.x引入了Tree shaking特性,对全局API进行分块,如果不使用某些功能,它将不会包含在基础包中

Vue3.x使用全局方法

import { nextTick } from 'vue'

nextTick(() => {})

Vue2.x中被涉及的API

  • Vue.nextTick
  • Vue.observable (使用reactive替换)
  • Vue.version
  • Vue.compile
  • Vue.set
  • Vue.delete

体验Tree shaking

Tree shaking无非就是做了两件事:

  • 编译阶段利用ES6 Module判断哪些模块已经加载
  • 判断那些模块和变量未被使用或者引用,进而删除多余代码

Vue2项目

创建vue2项目
vue create demo2
组件使用data属性
<template>
  <div id="app">
    {{ name }}
  </div>
</template>

<script>

export default {
  data() {
    return {
      name: '温情key'
    }
  }
}
</script>
打包

vendor.js放的是各个页面各个组件公用的一些代码

vue2打包

再使用computed, watch
<template>
  <div id="app">
    {{ name }}
    <br>
    <input type="text" v-model="count">
  </div>
</template>

<script>

export default {
  data() {
    return {
      name: '温情key',
      count: 1
    }
  },
  computed: {
    double() {
      return this.count * 2;
    }
  },
  watch: {
    count(newV, oldV) {
      console.log('count发生变化');
    }
  }
}
</script>
再次打包

在这里插入图片描述

总结

可以看到vendor.js体积没有发生变化,也就是说Vue2无论使没使用这些全局API都会被打包在基础包里面

Vue3项目

创建Vue3项目
vue create demo3
简单使用
<template>
  {{ state.name }}
</template>

<script>
import { defineComponent, reactive } from "vue";

export default defineComponent({
  setup() {
    const state = reactive({
      name: '温情key'
    });

    return { state }
  },
});
</script>
打包

vue3

再使用computed, watch
<template>
  {{ state.name }}
  <br>
  {{ double }}
  <input type="text" v-model="state.count">
</template>

<script>
import { defineComponent, reactive, computed, watch } from "vue";

export default defineComponent({
  setup() {
    const state = reactive({
      name: '温情key',
      count: 1
    });

    const double = computed((newV, oldV) => {
      return state.count * 2
    })

    watch(state, (newV, oldV) => {
      console.log('state发生变化');
    })

    return { state, double }
  },
});
</script>
再次打包

vue3打包

总结

可以看到比没使用computedwatch的包更大了,所以Vue3.x只有使用到的功能才会被打进包里

作用

通过Tree shaking,Vue3给我们带来的好处是:

  • 减少程序体积(更小)
  • 减少程序执行时间(更快)
  • 便于将来对程序架构进行优化(更友好)
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温情key

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值