Skip to content

Instantly share code, notes, and snippets.

@peterpme
Created March 8, 2024 14:52

Revisions

  1. peterpme created this gist Mar 8, 2024.
    54 changes: 54 additions & 0 deletions update-import.ts
    Original 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;
    }