返回
rollup技术揭秘系列十之includeStatements的内部原理
前端
2023-09-05 12:06:06
前言
在上一篇文章中,我们介绍了rollup技术中module.include()函数的基本原理。在本文中,我们将继续深入探讨includeStatements函数的内部原理。
includeStatements函数的内部原理
includeStatements函数的主要目的是将所有具有“hasEffects”的节点都打上included: true的标记。这样做是为了方便后续对字符串进行“删”、“改”的操作。
具体来说,includeStatements函数首先会创建一个新的对象,并将该对象作为参数传递给module.include()函数。
const included = new Set();
module.include(walker(source), included);
walker函数是一个遍历语法树的函数,它会将所有具有“hasEffects”的节点都添加到included对象中。
function walker(source) {
return {
Program(node, parent, scope) {
for (const stmt of node.body) {
if (hasEffects(stmt, scope)) {
included.add(stmt);
}
}
}
};
}
hasEffects函数是一个判断节点是否有副作用的函数。如果一个节点有副作用,那么它就会被添加到included对象中。
function hasEffects(node, scope) {
switch (node.type) {
case "AssignmentExpression":
case "UpdateExpression":
case "CallExpression":
case "NewExpression":
return true;
default:
return false;
}
}
结语
通过对includeStatements函数的分析,我们了解了rollup技术是如何处理具有“hasEffects”的节点的。这些知识对于我们理解rollup技术的内部原理是非常重要的。