181 - 《手撕源码 25:Rollup 3 上》
发布于 2022年9月5日
Rollup 和 Webpack 齐名,都是打包工具。通常大家用 Webpack 打包项目,用 Rollup 打包 npm 包,这在 Vite 出来之后有了些变化。著名的 Tree Shaking 也是源自 Rollup。Rollup 作者是大名鼎鼎的 Rich Harris,他也是 Svelte 的作者。目前的维护者是 lukastaegert。
趁着 Rollup 即将发布 3,翻了翻源码。时间有限,只看了 2 小时,理解比较浅,还有很多内容值得深挖。
1、Rollup 如何打包?
大家可能知道 rollup 的配置分 inputOptions 和 outputOptions 两部分,这和实现有关,所以实现也是分了两部分。
// 1、处理 input
const bundle = await rollup(inputOptions);
// 2、output 输出
await Promise.all(outputOptions.map(bundle.write));
input 的主体逻辑在 src/Graph.ts,代码是 await (new Graph()).build()
,这里会做三件事。
// 1、生成依赖图谱
this.generateModuleGraph();
// 2、给模块排序,同时标记 statement 到模块的引用
this.sortModules();
// 3、tree-shaking?
this.includeStatements();
生成依赖图谱时会通过 src/ModuleLoader.ts 添加入口模块,然后递归分析和添加其依赖。此时会生成大量 Module 实例,Module 通常(?)是文件,每个 Module 会做 transform 并返回 ast 等信息。
output 的主体逻