简体   繁体   中英

Babel plugin - How to transform JSX without react

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

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

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