[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)
      }  
    }
  };
}

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/12416212.html