Custom Babel Plugin to transform JSX/HTML tag to Json

Jhashal
3 min readAug 3, 2023

--

Objective here is to make simplest conversion of JSX file returning tags to transform into json

consider the basic app folder as below:

Project structure with code in yourapp/src/code.jsx, package.json, .babelrc and babelCustomPlugin folder for babel code

Here code to be transformed is in my-app/src/code.jsx, package.json, .babelrc and babelCustomPlugin folder contains src/index.js for babel custom plugin code.

Let’s take a look at our JSX (it is very basic a function containing unknown html like tags, you can add actual divs as well):

function render() { return ( <JsxToJson class=”test”> <title>mytitle</title> <body>mybody</body> <link>https://abc/</link> <abc> <bde> <a>efg1</a> <b></b> </bde> <bde> <a>efg2</a> </bde></abc> </JsxToJson> ) };

our .babelrc will have one basic preset, preset-env and a plugin to understand jsx along with our custom plugin

Please note:- the second plugin is the complete path of custom plugin code.Now let’s take a look at custom plugin:

Inside Function Declaration we have two function enter and exit both have path AST as input.
We now need to traverse the code by using path.
path.get(‘body’) will return our code function body with { return /**our tags **/;}
So our next task is to remove these extra symbols and text , we can do that by simply using replace such that the whole tag part becomes an xml string
Now we can use xml2json parser by installing in our project.
npm i xml2json
and in our babel code import as below:
var parser = require(‘xml2json’);
Now pass the xml string generated by replacing extras from path body.
as

var json =parser.toJson(xml);

this generates a JSON string.

Now in order to pass this to generated file we will have to manipulate path by “ path.insertBefore(t.valueToNode(JSON.parse(json)));”

and to remove anything extra being generated we can use path.remove() in exit function.

we are done with the code but how to run this. For that we just need to include below command in script section of your package.json:
“mybabel”: “babel src/code.jsx — out-file output/code.json”

Now when run npm run mybabel, it will take code.jsx as input and generate code.json as output as shown below:

here we got every tag used in json format.
Now you might also notice “use strict” on top which is default added by babel when transpiling our jsx , ts or js code. In case you don’t want that, feel free to add below plugin in your .babelrc file.

[“@babel/plugin-transform-modules-commonjs”, {strictMode: false}].

This will remove use strict from your transpiled output.

Happy Learning!! Hope this helps!!

--

--

Jhashal

Exploring & Learning each day and sharing the same