Created
November 16, 2024 02:37
-
-
Save drunewin/996a56113a61fee7049e15550268d69e to your computer and use it in GitHub Desktop.
Codemod that migrates deprecated JSX.Element type to ReactElement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Generated by Copilot | |
import { API, FileInfo, Options } from 'jscodeshift'; | |
export default function transformer(file: FileInfo, api: API, options: Options) { | |
const j = api.jscodeshift; | |
const root = j(file.source); | |
// Check if JSX.Element is used | |
const jsxElementUsage = root.find(j.TSTypeReference, { | |
typeName: { type: 'TSQualifiedName', left: { name: 'JSX' }, right: { name: 'Element' } }, | |
}); | |
if (jsxElementUsage.size() > 0) { | |
// Add import for ReactElement if it doesn't exist | |
const importDeclaration = root.find(j.ImportDeclaration, { | |
source: { value: 'react' }, | |
}); | |
if (importDeclaration.size() === 0) { | |
root.get().node.program.body.unshift( | |
j.importDeclaration( | |
[j.importSpecifier(j.identifier('ReactElement'))], | |
j.literal('react') | |
) | |
); | |
} else { | |
const reactImport = importDeclaration.find(j.ImportSpecifier, { | |
imported: { name: 'ReactElement' }, | |
}); | |
if (reactImport.size() === 0) { | |
importDeclaration.get().node.specifiers.push( | |
j.importSpecifier(j.identifier('ReactElement')) | |
); | |
} | |
} | |
// Replace JSX.Element with ReactElement | |
jsxElementUsage.forEach(path => { | |
j(path).replaceWith(j.tsTypeReference(j.identifier('ReactElement'))); | |
}); | |
} | |
return root.toSource(options); | |
} | |
export const parser = 'tsx'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment