Skip to content
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

Tree-Shaking的工作原理 #90

Open
bojue opened this issue Apr 26, 2020 · 0 comments
Open

Tree-Shaking的工作原理 #90

bojue opened this issue Apr 26, 2020 · 0 comments
Labels

Comments

@bojue
Copy link
Owner

bojue commented Apr 26, 2020

Tree-shaking (树摇)最早是由Rollup实现,是一种采用删除不需要的额外代码的方式优化代码体积的技术,webpack2借鉴了这个特性也增加了tree-shaking的功能。

tree-shaking 只能在静态modules下工作,在ES6之前我们使用CommonJS规范引入模块,具体采用require()的方式动态引入模块,这个特性可以通过判断条件解决按需记载的优化问题,具体如下

let module;

if(condition) {
    module =  require("HellowModule") ;
} else {
    module = requitre('BeyModule');  
}

但是CommonJS规范无法确定在实际运行前需要或者不需要某些模块,所以CommonJS不适合tree-shaking机制。

在JavaScript模块话方案中,只有ES6的模块方案:import()引入模块的方式采用静态导入,可以采用一次导入所以的依赖包再根据条件判断的方式,获取不需要的包,然后执行删除操作。

import hello from "Hellow";
import bey from "Bey";
import other from "Other"

if(condition) {
    // hello
} else {
    // bey
}

Tree-shaking的实现原理

利用ES6模块特性:

  • 只能作为模块顶层的语句出现
  • import的模块名只能是字符串常量
  • import binding 是 immutable的,引入的模块不能再进行修改

代码删除:

  • uglify:判断程序流,判断变量是否被使用和引用,进而删除代码

实现原理可以简单的概况:

  1. ES6 Module引入进行静态分析,故而编译的时候正确判断到底加载了那些模块
  2. 静态分析程序流,判断那些模块和变量未被使用或者引用,进而删除对应代码

参考

@bojue bojue added the Tool label May 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant