babel-plugin-r-sugar
Version:
A Babel plugin that adds Vue-style v-if directive support to React
54 lines (46 loc) • 1.67 kB
text/typescript
import type { NodePath } from '@babel/traverse';
import type { JSXElement, JSXAttribute } from '@babel/types';
import { types as t } from '@babel/core';
export function tablePlugin(path: NodePath<JSXElement>, t: typeof import('@babel/core').types) {
// 安全检查
if (!path.node?.openingElement?.name) return;
// 检查是否是 Table 组件
if (path.node.openingElement.name.type !== 'JSXIdentifier' ||
path.node.openingElement.name.name !== 'Table') {
return;
}
// 检查是否已经有 sticky 属性
const hasSticky = path.node.openingElement.attributes.some(
(attr): attr is JSXAttribute =>
attr.type === "JSXAttribute" && attr.name.name === "sticky"
);
if (hasSticky) return;
// 检查是否有 noBabel 属性且包含 'sticky'
const noBabelAttr = path.node.openingElement.attributes.find(
(attr): attr is JSXAttribute =>
attr.type === "JSXAttribute" && attr.name.name === "noBabel"
);
if (noBabelAttr?.value?.type === 'JSXExpressionContainer' &&
noBabelAttr.value.expression.type === 'ArrayExpression') {
const noBabelArray = noBabelAttr.value.expression.elements;
if (noBabelArray.some(
element => element?.type === 'StringLiteral' && element.value === 'sticky'
)) {
return;
}
}
// 创建 sticky 属性
const stickyAttribute = t.jsxAttribute(
t.jsxIdentifier("sticky"),
t.jsxExpressionContainer(
t.objectExpression([
t.objectProperty(
t.identifier("offsetHeader"),
t.numericLiteral(0)
)
])
)
);
// 添加 sticky 属性到组件
path.node.openingElement.attributes.push(stickyAttribute);
}