lundi 14 décembre 2020

Get source code of a JavaScript class constructor

I need to create a method GetCode returning a string with the source code of a constructor function for any class. For instance,

let code = GetCode (class CX {
  constructor () {
    this.x = 1
    this.y = 1
    this.fx ()
    this.fy ()
  }
  fx () {}
  fy () {}
})

should return some similar than this in the code variable:

`
  this.x = 1
  this.y = 1
  this.fx ()
  this.fy ()
`

For regular methods such as fx or fy a simple .toString invocation is enough. But when that is done on the constructor function, the returned string is the whole text of the class and not the inner source code of the function. I have tried to parse the string returned by CX.toString () to fetch exactly the fragment of text I need using tools such as JSCodeShift but the fingerprint is too heavy (5Mb).

I wonder if would be possible to devise a hack to get the string with the source code I need.





Aucun commentaire:

Enregistrer un commentaire