[AST Babel] Babel Template

For example we want to just conver a VariableDeclaration to

Foo.bar.otherBaz("one", 2);

 

We can use Babel template to do that:

export default function(babel) {
  const { types: t, template } = babel;

  return {
    name: "ast-transform", // not required
    visitor: {
      VariableDeclaration(path) {
          const templateString = `Foo.bar.BAZ(ONE, TWO)`
        const callExpressionBuilder = template(templateString)
        const callExpression = callExpressionBuilder({
            FOO: t.identifier('someFoo'),            
            BAZ: t.identifier('otherBaz'),
            ONE: t.stringLiteral('one'),
              TWO: t.numericLiteral(2)
        })
        path.replaceWith(callExpression)
      }  
    }
  };
}

 

posted @ 2020-03-04 21:18  Zhentiw  阅读(355)  评论(0编辑  收藏  举报