zl程序教程

您现在的位置是:首页 >  其它

当前栏目

[AST Babel] Babel Template

Template babel AST
2023-09-14 09:00:48 时间

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