Created
March 8, 2024 14:52
Revisions
-
peterpme created this gist
Mar 8, 2024 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,54 @@ export const parser = "tsx"; const importName = "A"; const importPath = "B"; const updatedImportPath = "C"; export default function transform(file, { jscodeshift: j }, options) { const source = j(file.source); // Create an AST of the given file let hasChanged = false; // Flag to track if any changes have been made source .find(j.ImportDeclaration) // Find all import declarations .filter((path) => path.node.source.value === importPath) // Filter to specific imports .forEach((path) => { const { specifiers, source } = path.node; const importedSpecifier = specifiers.find( (specifier) => specifier.imported && specifier.imported.name === importName ); if (importedSpecifier && source.value !== updatedImportPath) { if (specifiers.length === 1) { // If there's only one specifier, update the import path j(path).replaceWith( j.importDeclaration( [importedSpecifier], j.stringLiteral(updatedImportPath) ) ); } else { // If there are multiple specifiers, create a new import statement const newImport = j.importDeclaration( [importedSpecifier], j.stringLiteral(updatedImportPath) ); j(path).insertAfter(newImport); // Remove the specific specifier from the original import statement const updatedSpecifiers = specifiers.filter( (specifier) => specifier !== importedSpecifier ); j(path).replaceWith( j.importDeclaration(updatedSpecifiers, j.stringLiteral(importPath)) ); } hasChanged = true; } }); // Return the modified source if changes were made, otherwise return null return hasChanged ? source.toSource(options.printOptions) : null; }