Skip to main content

@babel/traverse

安装

¥Install

npm install --save @babel/traverse

用法

¥Usage

我们可以将它与 babel 解析器一起使用来遍历和更新节点:

¥We can use it alongside the babel parser to traverse and update nodes:

JavaScript
import * as parser from "@babel/parser";
import traverse from "@babel/traverse";

const code = `function square(n) {
return n * n;
}`;

const ast = parser.parse(code);

traverse(ast, {
enter(path) {
if (path.isIdentifier({ name: "n" })) {
path.node.name = "x";
}
},
});

此外,我们可以针对语法树中的特定 节点类型

¥Also, we can target particular node types in the Syntax Tree

JavaScript
traverse(ast, {
FunctionDeclaration: function(path) {
path.node.id.name = "x";
},
});

📖 在这里阅读完整的文档

¥📖 Read the full docs here