Created
April 26, 2018 19:15
-
-
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
This file contains 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 * 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