Skip to content

Instantly share code, notes, and snippets.

@peterpme
Created March 8, 2024 14:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterpme/c71aee3369a8009ada17fb1a48b641d1 to your computer and use it in GitHub Desktop.
Save peterpme/c71aee3369a8009ada17fb1a48b641d1 to your computer and use it in GitHub Desktop.
Update Import
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment