Estraverse 
Estraverse (estraverse)是 ECMAScript 遍历函数 esmangle项目。
文档
你可以在这里找到使用文档 wiki页面。
示例使用
下面的代码将输出在文件根目录下声明的所有变量。
estraverse.traverse(ast, {
enter: function (node, parent) {
if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration')
return estraverse.VisitorOption.Skip;
},
leave: function (node, parent) {
if (node.type == 'VariableDeclarator')
console.log(node.id.name);
}
});
我们可以用 this.skip, this.remove 和 this.break 函数,而不是使用Skip, Remove和Break。
estraverse.traverse(ast, {
enter: function (node) {
this.break();
}
});
而estraverse提供 estraverse.replace 函数。返回节点时 enter/leave,将当前节点替换为当前节点。
result = estraverse.replace(tree, {
enter: function (node) {
// Replace it with replaced.
if (node.type === 'Literal')
return replaced;
}
});
通过 visitor.keys 通过映射,我们可以扩展遍历功能。
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Extending the existing traversing rules.
keys: {
// TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ]
TestExpression: ['argument']
}
});
通过 visitor.fallback 选项,我们可以控制遇到未知节点时的行为。
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Iterating the child **nodes** of unknown nodes.
fallback: 'iteration'
});
当 visitor.fallback 是一个函数,我们可以确定在每个节点上访问哪个键。
// This tree contains a user-defined `TestExpression` node.
var tree = {
type: 'TestExpression',
// This 'argument' is the property containing the other **node**.
argument: {
type: 'Literal',
value: 20
},
// This 'extended' is the property not containing the other **node**.
extended: true
};
estraverse.traverse(tree, {
enter: function (node) { },
// Skip the `argument` property of each node
fallback: function(node) {
return Object.keys(node).filter(function(key) {
return key !== 'argument';
});
}
});
许可证
版权所有2012-2016 Yusuke Suzuki (推特: @Constellation)和其他贡献者。
重新分发和使用的源代码和二进制形式,有或没有 在满足下列条件的情况下,允许进行修改:
-
重新发布源代码必须保留上述版权 注意,此条件列表和以下免责声明。
-
以二进制形式重新发布必须复制上述版权 注意,本条件列表和以下免责声明中的 随发行版提供的文件和/或其他材料。
本软件由版权所有者和贡献者“按原样”提供。 以及任何明示或暗示的保证,包括但不限于 对适销性和适合某一特定目的的默示保证 是否认。在任何情况下,我都不承担任何责任 直接的、间接的、偶然的、特殊的、惩戒性的或后果性的损害 (包括但不限于,替代商品或服务的采购; 损失:失去使用、数据或利润;或业务中断),无论如何引起和 在任何责任理论中,无论是合同责任、严格责任还是侵权责任 (包括疏忽或其他)因使用 本软件即使被告知有这种损害的可能性。