简体   繁体   English

Babel 插件 - 如何在不做出反应的情况下转换 JSX

[英]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:我已经编写了自己的模块,该模块将 JSX 字符串作为参数并将其转换为 javascript object,所以我这样称呼它:

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:这行得通,但我真正需要的是在编译时将 JSX 转换为 object,所以我可以像普通的 JSX 表达式一样编写它:

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

and get the result from my function as output like so:并从我的 function 作为 output 得到结果,如下所示:

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.我不明白有很多像“babel-plugin-transform-jsx”这样的 babel 插件可以做到这一点,但是我想了解 babel 插件以及它们是如何工作的,这样我就可以自己制作了。

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?我试图分析上面提到的插件的代码,但仍然无法理解事情是如何工作的,例如,插件如何知道他正在使用 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我唯一想做的就是提取该 JSX,将其放入我的 function 并将其转换为函数的返回

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:我已经想通了,原来你可以使用path.toString()获取节点的代码,例如声明这样的访问者:

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这在 babel 插件手册中不存在,我认为这是一个不好的做法,但无论如何它是一个快速的解决方案,以防有人想知道

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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