react-vfor
Version:
`ReactVFor` is a Vite/React plugin that allows you to use Vue-like `v-for` syntax in React components.
2 lines (1 loc) • 1.85 kB
JavaScript
;const g=require("@babel/types"),b=require("@babel/traverse"),E=require("@babel/parser"),S=require("@babel/generator");function j(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const i in n)if(i!=="default"){const l=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,l.get?l:{enumerable:!0,get:()=>n[i]})}}return t.default=n,Object.freeze(t)}const e=j(g);function y(n){const[t,i]=n.split(" in ").map(u=>u.trim());let l=t,r=null;return t.includes(",")&&([l,r]=t.split(",").map(u=>u.trim())),{items:i,item:l,index:r}}function J(){return{name:"vite-plugin-vfor-react",enforce:"pre",transform(n,t){if(!t.endsWith(".jsx")&&!t.endsWith(".tsx"))return null;const i=E.parse(n,{sourceType:"module",plugins:["jsx","typescript"]});return b(i,{JSXElement(r){const s=r.node.openingElement.attributes.find(a=>e.isJSXAttribute(a)&&e.isJSXIdentifier(a.name,{name:"v-for"}));if(!s||!s.value)return;let c=null;if(e.isStringLiteral(s.value)?c=s.value.value:e.isJSXExpressionContainer(s.value)&&e.isStringLiteral(s.value.expression)&&(c=s.value.expression.value),!c)return;const{items:p,item:m,index:f}=y(c);try{const a=e.objectExpression(r.node.openingElement.attributes.filter(o=>!(e.isJSXAttribute(o)&&e.isJSXIdentifier(o.name,{name:"v-for"}))).map(o=>e.objectProperty(e.identifier(o.name.name),e.isJSXExpressionContainer(o.value)?o.value.expression:e.stringLiteral(o.value.value)))),d=e.callExpression(e.memberExpression(e.identifier("React"),e.identifier("createElement")),[e.identifier(r.node.openingElement.name.name),a,...r.node.children]),x=e.arrowFunctionExpression([e.identifier(m),e.identifier(f||"index")],d),v=e.jsxExpressionContainer(e.callExpression(e.memberExpression(e.identifier(p),e.identifier("map")),[x]));r.replaceWith(v)}catch{return}}}),{code:S(i,{},n).code,map:null}}}}module.exports=J;