问题
I really would like to know how I could follow module imports in a custom typescript transformer. As a matter of fact I would like to achieve the following:
I would like to find a function call like e.g. transform(PlaygroundComponent)
And then I would like to find the corresponding class (PlaygroundComponent) retrieved as an argument of the function call and adjust/transform it. This class may be imported from another file.
I am really wondering how I could achieve this. Currently I do not know how to follow the module import and get a hand of the class definition.
I would appreciate any help. Thanks. :)
Here is an even more detailed description of my problem:
=== Setup ===
File: source.ts
import { ttransformer } from "../ttransformer";
import { TestComponent } from "./test.component";
ttransformer(TestComponent);
This file is the main target for the custom typescript transformer.
File: ttransformer.ts
export function ttransformer(type: any): void {}
For now this is just a "marker" for the typescript transformer.
File: test.component.ts
export class TestComponent {}
Just a basic class which will be based as an argument to the transformer function.
=== Running ===
Running the custom typescript transformer with ts-patch on the file source.ts will do the following:
- The file source.ts is the main entry point. Therefore it will parse this file. However it will start parsing the imports of this file.
- First of all it will parse the file ttransformer.ts (first import statement).
- Secondly it will parse the file test.component.ts. (second import statement).
- Then it will continue with the rest of the file source.ts.
=== Problem ===
Because of that I have the following problem: The actual class I want to adjust is traversed before I know that I want to adjust it. I just know that the class should be modified because of ttransformer(PlaygroundComponent). And this line of code is the last stuff processed.
So I do not have the information which class I should transform at the correct point of time.
=== What I have in mind ===
Therefore I had two options in mind to solve this:
Follow the module import to find the specific class and adjust it then. So the transformer sees the line ttransformer(PlaygroundComponent) and then has to follow the import of PlaygroundComponent. Because it has to find the definition.
Or to traverse the AST twice, with two transformers. The first transformer finds all the classes which have to be transformed and the second one does the actual transformation. Then your suggestion is possible because I do know which classes have to be adjusted.
So this question is also somehow connected with my problem: Shared data with typescript transfromers
回答1:
You can use TypeChecker#getAliasedSymbol
.
Given the example code you shared, you would use typeChecker.getAliasedSymbol(argumentSymbol)
to get the base symbol for the import.
来源:https://stackoverflow.com/questions/61718877/typescript-transformer-follow-module-imports