babel-plugin-r-sugar
Version:
A Babel plugin that adds Vue-style v-if directive support to React
31 lines (25 loc) • 1.04 kB
text/typescript
import type { NodePath } from '@babel/traverse';
import type { JSXElement, JSXAttribute, JSXSpreadAttribute, Expression, JSXEmptyExpression } from '@babel/types';
import { types as t } from '@babel/core';
export function vIfPlugin(path: NodePath<JSXElement>, t: typeof import('@babel/core').types) {
// 安全检查
if (!path.node?.openingElement?.attributes) return;
const vIfAttribute = path.node.openingElement.attributes.find(
(attr): attr is JSXAttribute => attr.type === "JSXAttribute" && attr.name.name === "v-if"
);
if (!vIfAttribute || !vIfAttribute.value || vIfAttribute.value.type !== 'JSXExpressionContainer') return;
path.node.openingElement.attributes = path.node.openingElement.attributes.filter(
attr => attr !== vIfAttribute
);
const condition = vIfAttribute.value.expression;
if (condition.type === 'JSXEmptyExpression') return;
path.replaceWith(
t.jsxExpressionContainer(
t.conditionalExpression(
condition,
path.node,
t.nullLiteral()
)
)
);
}