react-live-unplugin
Version:
Turn React components into live code blocks with ease.
45 lines (44 loc) • 1.19 kB
JavaScript
import { transform } from "@babel/standalone";
function transformCode(code) {
const result = transform(code, {
presets: [
[
"typescript",
{
allExtensions: true,
isTSX: true
}
],
"react"
],
plugins: [
function removeImportsExports() {
return {
visitor: {
ImportDeclaration(path) {
path.remove();
},
ExportDefaultDeclaration(path) {
const declaration = path.node.declaration;
if (declaration.type === "Identifier") {
path.replaceWithSourceString(
`render(React.createElement(${declaration.name}))`
);
} else if (declaration.type === "FunctionDeclaration") {
const id = declaration.id?.name || "Anonymous";
path.replaceWithSourceString(
`render(React.createElement(${id}))`
);
}
},
ExportNamedDeclaration(path) {
path.remove();
}
}
};
}
]
});
return result.code;
}
export { transformCode };