tree shaking简单分析

文章梗概

  1. 什么是tree shaking

  2. 为什么需要tree shaking

  3. tree shaking原理

什么是tree shaking

tree shaking首先是由rollup的作者提出的,它是DCE(dead code elimination)的一个实现,通过tree shaking的分析,可以使你代码里没有使用的代码全部删除。然而它又区别于普通的dec,这里作者有一个比喻很形象

imagine that you made cakes by throwing whole eggs into the mixing bowl and smashing them up, instead of cracking them open and pouring the contents out. Once the cake comes out of the oven, you remove the fragments of eggshell, except that’s quite tricky so most of the eggshell gets left in there.

简单翻译一下就是,如果将dec比作制作蛋糕,传统的dec做法就是,将整个鸡蛋丢进碗里搅拌,然后放进烤箱,烤完之后从做好的蛋糕里,找到不需要的蛋壳扔掉,而tree shaking是将鸡蛋打破把蛋黄等有用的东西丢进碗里搅拌,最后直接做出蛋糕。

为什么需要tree shaking

主要还是为了减少页面的加载时间,将无用的代码删除,减少js包的大小,从而减少用户等待的时间,使用户不因为漫长的等待而离开。
那为什么已经有了dec,还要做tree shaking呢,根据作者的意思是,由于js静态语法分析的局限性,从已有代码里去删除代码不如去寻找真正使用的代码来的好。

tree shaking实现的原理

其实关于tree shaking的实现原理上文多少都有提到,用一句话解释就是,找到你整个代码里真正使用的代码,打包进去,那么没用的代码自然就剔除了。
然而事情并非说的那么简单,我们如何知道哪些代码有用,哪些代码没用呢?其实tree shaking得以实现,是依赖es6的module模块的。是es6的模块特性,奠定了tree shaking的实现基础。
关于es6 module的特性,大概有如下几点:

  1. 必须写在最外层,不能写在函数里

  2. import的语句具有和var一样的提升(hoist)特性。

具体还有哪些特性可以查一下文档。

tree shaking首先会分析文件项目里具体哪些代码被引入了,哪些没有引入,然后将真正引入的代码打包进去,最后没有使用到的代码自然就不会存在了。

你可能感兴趣的:(tree shaking简单分析)