Skip to content

Instantly share code, notes, and snippets.

@Grohden
Created October 29, 2024 16:47
Show Gist options
  • Save Grohden/411aa178103a33b1e1b1f6a5153b8048 to your computer and use it in GitHub Desktop.
Save Grohden/411aa178103a33b1e1b1f6a5153b8048 to your computer and use it in GitHub Desktop.
Refactor import change module in TS using ts-morph
import path from 'path';
import { Project } from 'ts-morph';
const targetModule = 'OLD_PACKAGE';
const targetNamedImport = 'Loading';
const newNamedImport = 'Loading';
const newImportModule = 'NEW_IMPORT';
const project = new Project({
tsConfigFilePath: path.join(__dirname, '../tsconfig.json'),
});
for (const file of project.getSourceFiles()) {
let changed = false;
for (const node of file.getImportDeclarations()) {
// we only care about imports from the sdk
const moduleName = node.getModuleSpecifier().getLiteralText();
if (moduleName !== targetModule) {
continue;
}
// we only care if the import is our target import
const namedImports = node.getNamedImports();
const targetImport = namedImports.find((namedImport) => {
return namedImport.getText() === targetNamedImport;
});
if (!targetImport) {
continue;
}
if (namedImports.length === 1) {
node.remove();
} else {
targetImport.remove();
}
// We already import the new module? just include the named import
const alreadyImportedDeclaration = file
.getImportDeclarations()
.find(
(importDeclaration) =>
importDeclaration.getModuleSpecifier().getLiteralText() ===
newImportModule,
);
if (alreadyImportedDeclaration) {
alreadyImportedDeclaration.addNamedImport(newNamedImport);
} else {
file.addImportDeclaration({
namedImports: [targetNamedImport],
moduleSpecifier: newImportModule,
});
}
console.log(`Refactored ${file.getFilePath()}`);
changed = true;
}
if (changed) {
file.emitSync();
}
}
project.saveSync();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment