-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
面试官:说说Vue 3.0中Treeshaking特性?举例说明一下? #67
Comments
这怎么是vue3中的tree shaking。 |
我先问你,如果是optionAPI ,rollup能做到treeshaking到没用到的API吗,而且rollup怎么是vite底层机制了,vite的生产环境只不过用rollup来打包 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
一、是什么
Tree shaking
是一种通过清除多余代码方式来优化项目打包体积的技术,专业术语叫Dead code elimination
简单来讲,就是在保持代码运行结果不变的前提下,去除无用的代码
如果把代码打包比作制作蛋糕,传统的方式是把鸡蛋(带壳)全部丢进去搅拌,然后放入烤箱,最后把(没有用的)蛋壳全部挑选并剔除出去
而
treeshaking
则是一开始就把有用的蛋白蛋黄(import)放入搅拌,最后直接作出蛋糕也就是说 ,
tree shaking
其实是找出使用的代码在
Vue2
中,无论我们使用什么功能,它们最终都会出现在生产代码中。主要原因是Vue
实例在项目中是单例的,捆绑程序无法检测到该对象的哪些属性在代码中被使用到而
Vue3
源码引入tree shaking
特性,将全局 API 进行分块。如果您不使用其某些功能,它们将不会包含在您的基础包中二、如何做
Tree shaking
是基于ES6
模板语法(import
与exports
),主要是借助ES6
模块的静态编译思想,在编译时就能确定模块的依赖关系,以及输入和输出的变量Tree shaking
无非就是做了两件事:ES6 Module
判断哪些模块已经加载下面就来举个例子:
通过脚手架
vue-cli
安装Vue2
与Vue3
项目Vue2 项目
组件中使用
data
属性对项目进行打包,体积如下图
为组件设置其他属性(
compted
、watch
)再一次打包,发现打包出来的体积并没有变化
Vue3 项目
组件中简单使用
将项目进行打包
在组件中引入
computed
和watch
再次对项目进行打包,可以看到在引入
computer
和watch
之后,项目整体体积变大了三、作用
通过
Tree shaking
,Vue3
给我们带来的好处是:参考文献
The text was updated successfully, but these errors were encountered: