How to use the isTryStatement function from @babel/types
Find comprehensive JavaScript @babel/types.isTryStatement code examples handpicked from public code repositorys.
@babel/types.isTryStatement is a function that checks if a given AST node is a try...catch statement.
GitHub: fecym/ast-share
11 12 13 14 15 16 17 18 19 20
const tryPlugin = { visitor: { AwaitExpression(path) { // 首先保证 await 语句没有被 try/catch 包裹 if (path.findParent(path => t.isTryStatement(path.node))) return; const parent = path.parent; let replacePath = null; if (t.isVariableDeclarator(parent) || t.isAssignmentExpression(parent)) { // 赋值和声明的方式结构类似,都是在 AwaitExpression 中 path 的 parentPath.parentPath 上的节点就是 blockStatement 所需要的的参数,可以直接这么替换
2
12
1
40 41 42 43 44 45 46 47 48
types.isStringLiteral(args[0]) && !hasBinding(ancestors, 'require') && !isInFalsyBranch(ancestors); if (isRequire) { let optional = ancestors.some(a => types.isTryStatement(a)) || undefined; addDependency(asset, args[0], {optional}); return; }
0
2
2
+ 3 other calls in file
How does @babel/types.isTryStatement work?
The @babel/types.isTryStatement is a method in the @babel/types package in JavaScript that checks if a given AST (Abstract Syntax Tree) node is a TryStatement node or not. It does this by checking the type property of the node and comparing it with the string value "TryStatement".
GitHub: Blue-Skie/YuanRenXue-Web
517 518 519 520 521 522 523 524 525 526
}, FunctionDeclaration(path) { let {body} = path.node.body; if (body.length == 2 && types.isFunctionDeclaration(body[0]) && types.isTryStatement(body[1])) { let sourceCode = path.toString(); if (sourceCode.includes("constructor") && sourceCode.includes("debugger") &&
0
0
1
+ 71 other calls in file
70 71 72 73 74 75 76 77 78 79
path.replaceWithMultiple([tryCatchAst]); return; } else if ( // 已经包含 try 语句则直接退出 t.isBlockStatement(path.node) && t.isTryStatement(parentPath.node) ) { return; } path = parentPath;
0
0
0
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
const t = require("@babel/types"); const node = t.tryStatement( t.blockStatement([ t.expressionStatement( t.callExpression(t.identifier("foo"), [t.identifier("bar")]) ), ]), t.catchClause( t.identifier("error"), t.blockStatement([ t.expressionStatement( t.callExpression(t.identifier("handleError"), [t.identifier("error")]) ), ]) ), t.blockStatement([]) ); console.log(t.isTryStatement(node)); // true
In this example, we create a try statement node using the t.tryStatement function provided by @babel/types and pass it to the t.isTryStatement function to check if it is a try statement node. The result of the function call is true, indicating that the node is a try statement.
@babel/types.identifier is the most popular function in @babel/types (20936 examples)