How to use the validate function from @babel/types
Find comprehensive JavaScript @babel/types.validate code examples handpicked from public code repositorys.
@babel/types.validate is a function that checks whether an object conforms to the AST specification of Babel.
135 136 137 138 139 140 141 142 143 144
traverse(visitor, state) { (0, _index.default)(this.node, visitor, this.scope, state, this); } set(key, node) { t.validate(this.node, key, node); this.node[key] = node; } getPathLocation() {
+ 31 other calls in file
114 115 116 117 118 119 120 121 122 123
} } else { items[index] = replacement; } t.validate(parent, key, items); parent[key] = items; } }
+ 139 other calls in file
How does @babel/types.validate work?
@babel/types.validate is a function provided by the Babel compiler that checks whether an object conforms to the Abstract Syntax Tree (AST) specification of Babel. To validate an object, you can call the validate function and pass in the object you want to validate, as well as an optional configuration object that specifies the type of the object you are validating. The validate function will then compare the object to the AST specification of Babel and throw an error if the object does not conform to the specification. If the object conforms to the specification, the function will return true. The @babel/types.validate function is useful for ensuring that AST nodes created programmatically or obtained from a third-party library are properly formatted and will work correctly with other Babel functions.
171 172 173 174 175 176 177 178 179
if (!this.container) { throw new ReferenceError("Container is falsy"); } if (this.inList) { t.validate(this.parent, this.key, [node]); } else { t.validate(this.parent, this.key, node); }
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
const { types: t } = require("@babel/core"); module.exports = function ({ types: t }) { return { visitor: { BinaryExpression(path) { const left = path.get("left"); const right = path.get("right"); const isValidLeft = t.validate(left.node, { type: "Expression" }); const isValidRight = t.validate(right.node, { type: "Expression" }); if (!isValidLeft || !isValidRight) { throw new Error("Invalid argument type"); } }, }, }; };
In this example, we define a Babel plugin that checks if the left and right operands of every binary expression are valid AST nodes. To do this, we use the t.validate function provided by @babel/types to validate each operand node and ensure that it conforms to the Expression type. If either operand is not a valid expression, we throw an error to indicate that the program is invalid. When this plugin is run on some JavaScript code, it will validate each binary expression and throw an error if either operand is not a valid expression.
@babel/types.identifier is the most popular function in @babel/types (20936 examples)