- 断定某个节点是否为指定类型
内置的 type 对象供给了很多可以直接用来断定节点类型的对象函数:
- BinaryExpression(path) {
- if (t.isIdentifier(path.node.left)) {
- // ...
- }
- }
或者同时以浅比较来查看节点属性:
我们可以经由过程 path.node.{property} 的方法来拜访 AST 中节点属性:
- BinaryExpression(path) {
- if (path.get('left').isIdentifier({ name: "n" })) {
- // ...
- }
- }
- 获取指定路径的父节点
有时刻我们须要大年夜某个指定节点开端向上遍历获取某个父节点,此时我们可以经由过程传入检测的回调来断定:
- path.findParent((path) => path.isObjectExpression());
- // 获取比来的函数声明节点
- path.getFunctionParent();
- 获取兄弟路径
如不雅某个路径存在于 Function 或者 Program 中的类似列表的构造中,那么其可能会包含兄弟路径:
- // 源代码
- var a = 1; // pathA, path.key = 0
- var b = 2; // pathB, path.key = 1
- var c = 3; // pathC, path.key = 2
- // 插件定义
- export default function({ types: t }) {
- return {
- visitor: {
- VariableDeclaration(path) {
- // if the current path is pathA
- path.inList // true
- path.listKey // "body"
- path.key // 0
- path.getSibling(0) // pathA
- path.getSibling(path.key + 1) // pathB
- path.container // [pathA, pathB, pathC]
- }
- }
- };
- }
- 停止遍历
在转化步调中,Babel 会遍历上一步生成的令牌流,根据设备对节点进行添加、更新与移除等操作;Babel 本身并没有进行转化操作,而是依附于外置的插件进行实际的转化。
部分情况下插件须要停止遍历,我们此时只须要在插件中添加 return 表达式:
- BinaryExpression(path) {
- if (path.node.operator !== '**')
推荐阅读
2009年6月,我省开端量刑规范化改革,是全国第二批试点省份。据介绍,海南最新版的量刑细则涵盖了23个常见着绫躯和罚金刑、缓刑实用,所涉的刑事犯法案件占到我省刑事案件的95%以上。此次>>>详细阅读
本文标题:JavaScript语法树与代码转化实践
地址:http://www.17bianji.com/lsqh/36429.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示