babel-plugin-r-sugar
Version:
A Babel plugin that adds Vue-style v-if directive support to React
37 lines (30 loc) • 926 B
text/typescript
// src/index.ts
import { PluginObj, types as t } from '@babel/core';
const reactVIfPlugin = function(babel: typeof import('@babel/core')) {
const { types: t } = babel;
return {
name: "babel-plugin-react-v-if",
visitor: {
JSXElement(path) {
const vIfAttribute = path.node.openingElement.attributes.find(
attr => attr.type === "JSXAttribute" && attr.name.name === "v-if"
);
if (!vIfAttribute) return;
path.node.openingElement.attributes = path.node.openingElement.attributes.filter(
attr => attr !== vIfAttribute
);
const condition = vIfAttribute.value.expression;
path.replaceWith(
t.jsxExpressionContainer(
t.conditionalExpression(
condition,
path.node,
t.nullLiteral()
)
)
);
}
}
};
};
export default reactVIfPlugin;