I am trying to create a tool working on specific types using TypeScript's TypeChecker API. I need to uniquely identify specific types - like Angular's DomSanitizer from @angular/platform-browser package. I have following code to get fully qualified name of the type
let type = typeChecker.getTypeAtLocation(node);
let fqn = typeChecker.getFullyQualifiedName(type.getSymbol());
However, this returns name which contains absolute path to the node_modules directory, such as
"/home/user/project/node_modules/@angular/platform-browser/platform-browser".DomSanitizer
I would like to remove the part which is project specific, to have only something like "@angular/plaform-browser/platform-browser".DomSanitizer . I would prefer to use TypeScript API rather than doing some string operations on this value, as I expect the API to be more robust.
If you know what the project root is, you can use NodeJS's path.relative method for this:
import * as path from 'path'
const type = typeChecker.getTypeAtLocation(node);
const fqn = typeChecker.getFullyQualifiedName(type.getSymbol());
const projectRoot = '/home/user/project/node_modules/'
const relativePath = path.relative(projectRoot, fqn)
console.log(relativePath) // should print @angular/plaform-browser/platform-browser.DomSanitizer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With