You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import{ASTPath,CallExpression,FunctionExpression,ImportDeclaration,MemberExpression,Transform,}from'jscodeshift';consttransform: Transform=(file,api,options)=>{constj=api.jscodeshift;constroot=j(file.source);constimportsRequired=newSet<string>();// Replace JSX expression {<expression>.map(fn)} with <For each={expression}>{fn}</For>root.find(j.JSXExpressionContainer).filter(path=>{// We only care about JSX expression containers whose parents are JSX elements.// (in other words, exclude attribute expressions.)if(path.parent.node.type==='JSXElement'&&path.node.expression.type==='CallExpression'){constcall=path.node.expression;if(call.callee.type==='MemberExpression'&&call.callee.property.type==='Identifier'&&call.callee.property.name==='map'){returntrue;}}returnfalse;}).replaceWith(path=>{constcall=path.node.expressionasCallExpression;constcallee=call.calleeasMemberExpression;importsRequired.add('For');returnj.jsxElement.from({openingElement: j.jsxOpeningElement(j.jsxIdentifier('For'),[j.jsxAttribute.from({name: j.jsxIdentifier('each'),value: j.jsxExpressionContainer.from({expression: callee.object,}),}),]),closingElement: j.jsxClosingElement(j.jsxIdentifier('For')),selfClosing: false,children: [j.jsxExpressionContainer.from({expression: call.arguments.at(0)asFunctionExpression,}),],});});// See whether we need to add any importsif(importsRequired.size>0){// Look for solid-js importletlastImport: ASTPath<ImportDeclaration>|null=null;letsolidImport=root.find(j.ImportDeclaration).forEach(path=>{lastImport=path;}).filter(path=>path.node.source.value==='solid-js').forEach(path=>{if(!path.node.specifiers){path.node.specifiers=[];}path.node.specifiers?.forEach(spec=>{if(spec.type==='ImportSpecifier'){importsRequired.delete(spec.imported.name);}});for(constsymbolofimportsRequired){path.node.specifiers.push(j.importSpecifier.from({imported: j.jsxIdentifier(symbol),}));}});if(solidImport.length==0){// Insert new solid import statement.constsolidImport=j.importDeclaration.from({source: j.stringLiteral('solid-js'),specifiers: Array.from(importsRequired).map(symbol=>j.importSpecifier.from({imported: j.jsxIdentifier(symbol),})),});lastImport!.insertAfter(solidImport);}}returnroot.toSource({quote: 'single'});};exportdefaulttransform;
The text was updated successfully, but these errors were encountered:
Input code
Expected Output
Additional context
Here's a codemod which does this:
The text was updated successfully, but these errors were encountered: