简体   繁体   中英

JS creating babel plugin: how to get arguments of anonymous function

I am trying to create a plugin which detects execution of function while it transpiles and returns arguments of it

For example:

code:

testFN("hello");
testFN("world");

would return while babel transpiling:

hello
world

I created a babel plugin that can detect that function and output its parameters, but I cannot find arguments inside it

So it currently looks like this

module.exports = function ({ types: t }) {
  return {
    visitor: {
      Identifier(path) {
        if (path.node.name === 'testFN') {
          console.log(path.node);
        }
      },
    },
  };
};

It outputs:

Node {
  type: 'Identifier',
  start: 753,
  end: 759,
  loc:
   SourceLocation {
     start: Position { line: 19, column: 8 },
     end: Position { line: 19, column: 14 },
     identifierName: 'testFN' },
  name: 'testFN' }
Node {
  type: 'Identifier',
  start: 830,
  end: 836,
  loc:
   SourceLocation {
     start: Position { line: 23, column: 2 },
     end: Position { line: 23, column: 8 },
     identifierName: 'testFN' },
  name: 'testFN' }

I tried to use AST browser, but it gives different object path which i cannot reach in my babel plugin code https://astexplorer.net/#/gist/763d13950ad0334ac8ea3187464fcdbf/295a8fd8640210cee586444a58445401e8baa690

How can access arguments of my function though babel?

Thanks

Stupid me - tried to get argument trough Identifier. I needed to get it though CallExpression. Cheers

Code:

// eslint-disable-next-line func-names
module.exports = function ({ types: t }) {
  return {
    visitor: {
      CallExpression(path, { file }) {
        if (path.node.callee.name === "testFN") {
          console.log(path.node.arguments[)
        }
      },
    },
  };
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM