eslint-codemod-utils
Version:
A collection of AST helper functions for more complex ESLint rule fixes.
36 lines (35 loc) • 1.21 kB
JavaScript
import { jsxAttribute, jsxClosingElement, jsxElement, jsxIdentifier, jsxOpeningElement, literal, } from '..';
export const jsx = function (type, props, ...children) {
if (!type) {
return;
}
if (typeof type === 'function') {
// merge props and children
const componentProps = {
...props,
// @ts-expect-error
children: (props.children || []).concat(children),
};
// render the function
const element = type(componentProps);
return element;
}
const filteredChildren = children.filter(Boolean);
const selfClosing = !Boolean(filteredChildren.length);
const name = jsxIdentifier(type);
return jsxElement({
openingElement: jsxOpeningElement({
name,
selfClosing,
attributes: Object.keys(props).map((prop) => {
return jsxAttribute({
name: jsxIdentifier(prop),
value: literal('hello'),
});
}),
}),
closingElement: selfClosing ? null : jsxClosingElement({ name }),
// @ts-expect-error
children: filteredChildren.map(jsx),
});
};