Skip to content

Instantly share code, notes, and snippets.

@stephenh
Created November 29, 2024 00:45
Show Gist options
  • Save stephenh/12b8335ed209c759076b14e1420dd947 to your computer and use it in GitHub Desktop.
Save stephenh/12b8335ed209c759076b14e1420dd947 to your computer and use it in GitHub Desktop.
Remove tsconfig paths to relative imports
import * as path from "path";
import { Project } from "ts-morph";
function getRelativePath(fromPath: string, toPath: string): string {
let relativePath = path.relative(path.dirname(fromPath), toPath);
if (!relativePath.startsWith(".")) {
relativePath = "./" + relativePath;
}
return relativePath.replace(/\\/g, "/");
}
function transformImports() {
const project = new Project({
tsConfigFilePath: "tsconfig.json",
});
const sourceFiles = project.getSourceFiles();
const compilerOptions = project.getCompilerOptions();
const paths = compilerOptions.paths || {};
sourceFiles.forEach((sourceFile) => {
let modified = false;
const imports = sourceFile.getImportDeclarations();
imports.forEach((importDecl) => {
const moduleSpecifier = importDecl.getModuleSpecifierValue();
for (const [alias, targets] of Object.entries(paths)) {
const aliasPattern = alias.replace("/*", "");
if (moduleSpecifier.startsWith(aliasPattern)) {
const target = targets[0].replace("/*", "");
const importPath = moduleSpecifier.replace(aliasPattern, target);
const absolutePath = path.resolve(process.cwd(), importPath);
const relativePath = getRelativePath(sourceFile.getFilePath(), absolutePath);
importDecl.setModuleSpecifier(relativePath);
modified = true;
}
}
});
if (modified) {
sourceFile.save();
}
});
}
transformImports();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment