0

I want to be able to "reflect" function parameters and get their names, it should work for destructured object parameters as well, example

parseParams('({a, b}) => 1')

and I want the result to be something like

[["a", "b"]]

so here I know that that the function a first argument which is an object with keys a & b. I expect some code like this exists somewhere inside the guts of babel, but I can't find it easily

gafi
  • 12,113
  • 2
  • 30
  • 32
  • Please refer to the following question http://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically-from-javascript – dmlittle Jun 14 '16 at 06:19
  • 1
    Babel uses [Babylon](https://github.com/babel/babylon) for parsing ES6 code. There are others as well, e.g. [esprima](http://esprima.org/). – Bergi Jun 14 '16 at 06:21
  • @dmlittle: None of those includes a full ES6 parser. – Bergi Jun 14 '16 at 06:23
  • @dmlittle I can't find something in that thread that works with destructuring – gafi Jun 14 '16 at 06:47
  • Maybe look into how Angularjs does this. It does this so it can find which modules to inject and is also ES6 compliant. I don't have any links of hand but You should be able to find something looking through their GitHub. – ste2425 Jun 14 '16 at 06:57
  • 1
    Maybe this helps: http://astexplorer.net/#/fgWU3KGrlk – Felix Kling Jun 14 '16 at 14:11

1 Answers1

1

I found a way with babylon

const parsed = require("babylon").parse('({a,b}) => 1', {
            sourceType: 'script' });

    // the keys of the object will be available as
const key1 = parsed.program.body[0].expression.params[0].properties[0].key.name // a
const key2 = parsed.program.body[0].expression.params[0].properties[1].key.name // b

working demo https://tonicdev.com/57205506e8bb3a1100675026/575fa8ce3154641300347910

gafi
  • 12,113
  • 2
  • 30
  • 32