Skip to content

Instantly share code, notes, and snippets.

@rifler
Created April 26, 2018 19:15
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 rifler/39fdcd92e78505bbc94dc5b9f845292b to your computer and use it in GitHub Desktop.
Save rifler/39fdcd92e78505bbc94dc5b9f845292b to your computer and use it in GitHub Desktop.
Replace absolute paths by relative, based on baseUrl and paths fields from tsconfig.json
import * as nodePath from 'path';
import paths from 'tsconfig-paths';
import * as tsconfig from 'tsconfig-extends';
import Project from 'ts-simple-ast';
// use `tsconfig-extends` module cause it can recursively apply "extends" field
const compilerOptions = tsconfig.load_file_sync('./tsconfig.json');
const absoluteBaseUrl = nodePath.join(process.cwd(), compilerOptions.baseUrl);
const matchPathFunc = paths.createMatchPath(absoluteBaseUrl, compilerOptions.paths || {});
const project = new Project({ compilerOptions });
project.addExistingSourceFiles('./src/**/*.{ts,tsx}');
const sourceFiles = project.getSourceFiles();
sourceFiles.forEach(async (sourceFile) => {
const importExportDeclarations = [
...sourceFile.getImportDeclarations(),
...sourceFile.getExportDeclarations(),
];
const sourceFileAbsolutePath = sourceFile.getFilePath();
let sourceFileWasChanged = false;
for (const declaration of importExportDeclarations) {
// if module seems like absolute
if (!declaration.isModuleSpecifierRelative()) {
const value = declaration.getModuleSpecifierValue();
// try to find relative module for it
const absolutePathToDepsModule = matchPathFunc(value);
// and if relative module really exists
if (absolutePathToDepsModule) {
const resultPath = nodePath.relative(sourceFileAbsolutePath, absolutePathToDepsModule);
// replace absolute to relative
declaration.setModuleSpecifier(resultPath);
sourceFileWasChanged = true;
}
}
}
if (sourceFileWasChanged) {
await sourceFile.save();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment