Babel Plugins 101

Babel Plugins 101

Writing a Babel Plugin is simpler than you may think!

767ad16f5fb26d68793d0ffa86b37aef?s=128

Giuseppe Gurgone

February 09, 2020
Tweet

Transcript

  1. plugins 101

  2. giuseppe.pizza

  3. <Pizza ingredients={[ 'tomato sauce', 'mozzarella', 'ham', 'pineapple' ]} /> Let’s

    transform some code for the good
  4. <Pizza ingredients={[ 'tomato sauce', 'mozzarella', 'ham', 'pineapple' ⚠ ]} />

    Remove pineapple
  5. ASTExplorer.net

  6. ASTExplorer.net 1. Source Code 2. AST 3. Plugin 4. Result

  7. AST - Abstract Syntax Tree

  8. Pro-tip Use AST Explorer to find out the name of

    a piece of syntax! JSXAttribute ingredients JSXIdentifier {} JSXExpressionContainer [] ArrayExpression ‘pineapple’ StringLiteral
  9. Plugins: Visitors to visit and transform the AST

  10. Visitor: path has info about current path and node

  11. Our Plugin: remove pineapple

  12. Step1: grab the JSXExpressionContainer

  13. Step2: grab the ArrayExpression

  14. Step3: remove pineapple from arrExpr.node.elements

  15. Done

  16. Next? Replace a path and more Babel Handbook Create a

    node: Babel Types babeljs.io/docs/en/babel-types
  17. Conclusion Babel is awesome! It is more than a tool

    for transpiling new syntax! Writing Babel plugins is empowering and my favorite (programming) hobby. True Test Drive Development: expect(transpiled).toEqual(expected); AST Explorer, Handbook and Babel Types Docs! Thank: @fkling42, James Kyle and the Babel contributors!
  18. Thank You giuseppe.pizza