Just personal notes that I'm collecting as I learn more about how to write plugins for babel.
- Making a property on an object
t.property('init', t.identifier('foo'), t.literal('bar'))
- Not sure why, but the kind of the property is
init
, second parameter is key of the object, final one is the value
- Value to node
t.valueToNode()
- Remove a node
this.dangerouslyRemove()
- A member expression would be something like
Object.defineProperties
t.memberExpression(t.identifier('Object'), t.identifier('defineProperties'))
- An assignment expression takes in
- operator
- left
- right
t.assignmentExpression('=', t.identifier('foo'), t.valueToNode(1))
- A Call Expression is simply a function or method call expression
t.callExpression(
// Callee
t.memberExpression(
t.identifier('Object'),
t.identifier('defineProperties')
),
// Arguments
[t.valueToNode(1)]
)
Path: babel/packages/babel/src/traversal/path/evaluation.js
Functions:
function evaluate(): { confident: boolean; value: any }
- Walk the input
node
and statically evaluate it.
- Walk the input
function evaluateTruthy(): boolean
- Walk the input
node
and statically evaluate if it's truthy.
- Walk the input
You actually have the ability to try and evaluate
certain expressions when parsing the AST. For example, if you had a BinaryExpression
, you could evaluate
both the left and the right side.
visitor: {
BinaryExpression() {
const { value: left } = this.get('left').evaluate();
const { value: right } = this.get('right').evaluate();
// Fully evaluated BinaryExpression
return t.valueToNode(left + right);
}
}
In addition, you also have access to an evaluateTruthy
function that will walk the input node
and statically evaluate if it's truthy.