UNPKG

@babel/plugin-transform-react-inline-elements

Version:
63 lines (60 loc) 1.9 kB
import { declare } from '@babel/helper-plugin-utils'; import helper from '@babel/helper-builder-react-jsx'; import { types } from '@babel/core'; const index = declare(api => { api.assertVersion("^7.0.0-0 || ^8.0.0"); function hasRefOrSpread(attrs) { for (let i = 0; i < attrs.length; i++) { const attr = attrs[i]; if (types.isJSXSpreadAttribute(attr)) return true; if (isJSXAttributeOfName(attr, "ref")) return true; } return false; } function isJSXAttributeOfName(attr, name) { return types.isJSXAttribute(attr) && types.isJSXIdentifier(attr.name, { name: name }); } const visitor = helper({ filter(node) { return node.type === "JSXElement" && !hasRefOrSpread(node.openingElement.attributes); }, pre(state) { const tagName = state.tagName; const args = state.args; if (types.react.isCompatTag(tagName)) { args.push(types.stringLiteral(tagName)); } else { args.push(state.tagExpr); } }, post(state, pass) { state.callee = pass.addHelper("jsx"); const props = state.args[1]; let hasKey = false; if (types.isObjectExpression(props)) { const keyIndex = props.properties.findIndex(prop => types.isIdentifier(prop.key, { name: "key" })); if (keyIndex > -1) { state.args.splice(2, 0, props.properties[keyIndex].value); props.properties.splice(keyIndex, 1); hasKey = true; } } else if (types.isNullLiteral(props)) { state.args.splice(1, 1, types.objectExpression([])); } if (!hasKey && state.args.length > 2) { state.args.splice(2, 0, types.buildUndefinedNode()); } state.pure = true; } }); return { name: "transform-react-inline-elements", visitor }; }); export { index as default }; //# sourceMappingURL=index.js.map