Skip to content

Instantly share code, notes, and snippets.

@joshblack
Last active August 29, 2015 14:26
Show Gist options
  • Save joshblack/a6b9030138146fd02ca4 to your computer and use it in GitHub Desktop.
Save joshblack/a6b9030138146fd02ca4 to your computer and use it in GitHub Desktop.
Taking notes while I'm messing around with Babel

Babel Notes

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)] 
  )

Evaluation

Path: babel/packages/babel/src/traversal/path/evaluation.js

Functions:

  • function evaluate(): { confident: boolean; value: any }
    • Walk the input node and statically evaluate it.
  • function evaluateTruthy(): boolean
    • Walk the input node and statically evaluate if it's truthy.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment