构建节点
构建器的方法名称就是您想要的节点类型的名称,除了第一个字母小写。 例如,如果您想建立一个您可以使用 t.memberExpression(…)
这些构建器的参数由节点定义决定。 有一些正在做的工作,以生成易于阅读的文件定义,但现在他们都可以在此处找到。.
节点定义如下所示:
在这里你可以看到关于这个特定节点类型的所有信息,包括如何构建它,遍历它,并验证它。
通过查看 生成器
属性, 可以看到调用生成器方法所需的3个参数 (t. 情况
).
生成器: ["object", "property", "computed"],
// Example
// because the builder doesn't contain `async` as a property
var node = t.classMethod(
"constructor",
t.identifier("constructor"),
params,
)
// set it manually after creation
node.async = true;
You can see the validation for the builder arguments with the
fields
object.
You can see that needs to be an Expression
, property
either needs to be an Expression
or an Identifier
depending on if the member expression is computed
or not and computed
is simply a boolean that defaults to false
.
So we can construct a MemberExpression
by doing the following:
t.memberExpression(
t.identifier('object'),
t.identifier('property')
// `computed` is optional
Which will result in:
object.property
Well if we look at the definition of Identifier
we can see that it has an aliases
property which states that it is also an expression.
So since MemberExpression
is a type of Expression
, we could set it as the object
of another MemberExpression
:
t.memberExpression(
t.memberExpression(
t.identifier('member'),
t.identifier('expression')
),
t.identifier('property')
Which will result in:
member.expression.property
It’s very unlikely that you will ever memorize the builder method signatures for every node type. So you should take some time and understand how they are generated from the node definitions.
You can find all of the actual and you can see them documented here