279 - 《调研 Tree Shaking 实现》
发布于 2023年3月28日
调研了下 Tree Shaking 的实现,没实操,有些细节的点还不够清楚。以下是笔记。
什么是 tree-shaking?
比如两个文件 a.js 和 main.js 如下,其中 main.js 是入口文件。可以看出,a.js 里的 b 没有被用到,所以产物里不应该出现。这就是 tree-shaking。
// a.js
export const a = 1;
export const b = 2;
// main.js
import { a } from './a';
console.log(a);
Tree shaking, also known as dead code elimination, is the practice of removing unused code in your production build. It’s important to ship as little code to your end-users as possible. By statically analyzing our source code, we can determine what’s not being used and exclude it from our final bundle.
树摇,也称为死代码消除,是在生产构建中删除未使用的代码的实践。将尽可能少的代码发送给最终用户非常重要。通过静态分析源代码,我们可以确定哪些内容没有被使用,并将其从最终捆绑包中排除掉。
上面的例子是最基础的 export 级的 tree-shaking。而 tree-shaking 要做好,需要在安全的基础上,尽可能多删除无用代码。所以,还会有大量进阶的例子。比如:
- 支持
export *
和import *
(可能有多级) - 支持内部模块 tree-shaking(比如内部的一个变量、函数或 class 没有被用到,也可以删除)
- 支持 cjs(cjs 是动态 require 的,理论上不能 tree-shaking,但其实没用到动态 require 功能的 cjs 也可以支持)
- 支持 package.json 中的 sideEffects 声明(用于声明当前包的是否有副作用,有则不参与 tree-shaking)
- 支持
await import()
(rollup 不支持) - 支持
c