UNPKG

eslint-codemod-utils

Version:

A collection of AST helper functions for more complex ESLint rule fixes.

45 lines (44 loc) 1.51 kB
import { jsxAttribute, jsxClosingElement, jsxElement, jsxIdentifier, jsxOpeningElement, literal, } from '..'; export const jsx = function (type, props, ...children) { if (!type) { return; } if (typeof type === 'function') { const existing = Array.isArray(props.children) ? props.children : props.children ? [props.children] : []; const componentProps = { ...props, children: [...existing, ...children], }; return type(componentProps); } const filteredChildren = children.filter((child) => Boolean(child)); const selfClosing = filteredChildren.length === 0; const name = jsxIdentifier(type); return jsxElement({ openingElement: jsxOpeningElement({ name, selfClosing, attributes: Object.keys(props) .filter((key) => key !== 'children') .map((prop) => { return jsxAttribute({ name: jsxIdentifier(prop), value: literal('hello'), }); }), }), closingElement: selfClosing ? null : jsxClosingElement({ name }), children: filteredChildren .map((child) => { if (typeof child === 'string' || typeof child === 'number') { return undefined; } return child; }) .filter((child) => Boolean(child)), }); };