0

I have wrote my own module which takes a JSX string as a parameter and turns it into a javascript object, so I call it like so:

import parser from 'own-parser'
console.log(parser("<h1>Hello world</h1>"))

This works, but what I actually need is to transform the JSX into the object when it compiles, so I could write it like a normal JSX expression:

var jsx = <h1>Hello World</h1>

and get the result from my function as output like so:

var jsx = {element: 'h1', children:[/*...*/]}

I undrestand there are many babel plugins like "babel-plugin-transform-jsx" which can accomplish this, but I want to learn about babel plugins and how they work so I can make my own.

I've tried to analize the code of the plugin mentioned above but still cannot understand how things work, for example, how does the plugin know that he is working with a JSXElement?

The only thing I am trying to do is to extract that JSX, put it inside my function and transform it into the function's return

How can I do that? Thanks

  • You could look at the existing Babel JSX transform, but neither your input nor your output match how JSX is handled. – jonrsharpe Apr 09 '20 at 20:54
  • @jonrsharpe How aren't my input and output match JSX handling? If I use the existing babel jsx transform, my code above will transform into something similar, I just try to replicate the same functionality so I can understand how babel plugins work thats all, I could present a different example, not just jsx transform – Nick Pashkov Apr 09 '20 at 21:02
  • Then I'd suggest starting with https://babeljs.io/docs/en/plugins#plugin-development – jonrsharpe Apr 09 '20 at 21:21

1 Answers1

1

I've figured it out, turns out you can get the code of a node with path.toString(), for example to declare a visitor like that:

JSXElement(path, state) {
  if (path.parentPath.type != "JSXElement") {
     const parsed = parser(path.toString())
     path.replaceWithSourceString(JSON.stringify(parsed))
  }
}

This is not present in the babel plugin handbook, I suppose this is a bad practice, but anyways it is a quick solution in case anyone wondered