Created
January 15, 2023 09:14
-
-
Save sanketsahu/a885903d626f999ec924a3efdbb3ca1a to your computer and use it in GitHub Desktop.
Running Babel in the browser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from "react"; | |
const Babel = require("@babel/standalone"); | |
const Parser = require("@babel/parser"); | |
function isStyledFunctionCall(node) { | |
return ( | |
node.type === 'CallExpression' && | |
node.callee.type === 'Identifier' && | |
node.callee.name === 'styled' && | |
node.callee.object.type === 'Import' && | |
node.callee.object.source.value === 'dank-style' | |
); | |
} | |
// Simple plugin that converts every identifier to "LOL" | |
function lolizer(inp) { | |
return { | |
visitor: { | |
CallExpression: function(path){ | |
console.log("TEST", path.match); | |
if (isStyledFunctionCall(path.node)) { | |
console.log("YES"); | |
// code to be executed if the node at the current path in the AST | |
// is a function call named "styled" that is imported from a library called "dank-style" | |
} | |
} | |
}, | |
}; | |
} | |
Babel.registerPlugin("lolizer", lolizer); | |
if(typeof window != "undefined") window.Babel = Babel; | |
function babelPlugin(code) { | |
let transformed = code; | |
try { | |
console.log('!@!@!', Parser.parse(code)); | |
transformed = Babel.transform(code, { | |
//presets: ["@babel/preset-env"], | |
plugins: ["lolizer"], | |
}); | |
} catch (e) { | |
return code; | |
} | |
return transformed.code; | |
} | |
export default function Home() { | |
const [val, setVal] = useState(""); | |
return ( | |
<div style={{ display: "flex" }}> | |
<div> | |
<textarea | |
onChange={(e) => setVal(babelPlugin(e.target.value))} | |
style={{ height: "calc(100vh - 10px)", width: "calc(50vw - 10px)" }} | |
></textarea> | |
</div> | |
<div> | |
<pre | |
style={{ height: "calc(100vh - 10px)", width: "calc(50vw - 10px)" }} | |
> | |
{val} | |
</pre> | |
</div> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment