Generic JSX for Babel JavaScript AST

node v8.17.0
version: 5.0.0
Node constructors in Babel use non-named parameters. This small snippet will iterate over all the node types in Babel and create named-parameter equivalents. So for example, new Identifier({ name: "variable }) vs. Identifier("variable"):
/* @jsx (curry(_=>eval(_))) */ var { curry } = require("generic-jsx"); var types = require("babel-types"); var NODE_FIELDS = types.NODE_FIELDS; var names = Object.keys(NODE_FIELDS); var Node = { }; for (let name of names) Node[name] = (properties) => { var children = properties.children || []; var args = []; for (let field in NODE_FIELDS[name]) if (properties.hasOwnProperty(field)) args.push(properties[field]); else if (children.length) args.push(children.shift()()); return types[name.charAt(0).toLowerCase() + name.substr(1)].apply(this, args); }
Once we've done this, it naturally works with JSX syntax. This means we have a very pleasing syntax for writing syntax trees:
<Node.MemberExpression computed = { false }> <Node.ThisExpression/> <Node.Identifier name = "length"/> </Node.MemberExpression>()
var CodeGenerator = require("babel-generator").default; function generate(anAST) { return (new CodeGenerator(anAST)).code; } generate(<Node.MemberExpression computed = { false }> <Node.ThisExpression/> <Node.Identifier name = "length"/> </Node.MemberExpression>())

no comments

    sign in to comment