Created
December 12, 2023 18:23
-
-
Save codebutler/f8fa8049621f290d434cf97067035c18 to your computer and use it in GitHub Desktop.
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 characters
import { Project, SyntaxKind } from "ts-morph"; | |
/** | |
* This script converts all "barrel" imports to fully qualified imports. | |
* | |
* Use 'bun' to run the script: | |
* bun run morphs/fully-qualified-gen-imports.ts | |
*/ | |
const project = new Project({ | |
tsConfigFilePath: "tsconfig.json", | |
}); | |
const barrelFile = project.getSourceFileOrThrow("src/gen/model/index.ts"); | |
const exportedModules = barrelFile | |
.getExportDeclarations() | |
.map((exp) => { | |
const referencedSourceFile = exp.getModuleSpecifierSourceFileOrThrow(); | |
const moduleSpecifier = project | |
.getRootDirectories()[0] | |
.getRelativePathAsModuleSpecifierTo(referencedSourceFile.getFilePath()) | |
// There's probably some way to resolve this using the "paths" in tsconfig but I couldn't figure it out | |
.substring("./src/".length); | |
const namedExports = referencedSourceFile.getExportedDeclarations(); | |
return Array.from(namedExports.keys()).map((name) => ({ | |
name, | |
moduleSpecifier, | |
})); | |
}) | |
.flat(); | |
project.getSourceFiles().forEach((sourceFile) => { | |
sourceFile.getImportDeclarations().forEach((importDeclaration) => { | |
if (importDeclaration.getModuleSpecifierValue() === "gen/model") { | |
const namedImports = importDeclaration.getNamedImports(); | |
namedImports.forEach((namedImport) => { | |
const correspondingExport = exportedModules.find( | |
(exp) => exp.name === namedImport.getName(), | |
); | |
if (correspondingExport) { | |
sourceFile.addImportDeclaration({ | |
moduleSpecifier: correspondingExport.moduleSpecifier, | |
namedImports: [namedImport.getName()], | |
}); | |
} | |
}); | |
importDeclaration.remove(); | |
} | |
}); | |
sourceFile.saveSync(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment