This is a short and summarized version of how to parse Typescript from source. You can read more about Typescript AST at the official documentation.
If you want to know about parsing Javascript, please read https://medium.com/allenhwkim/how-to-parse-javascript-from-source-ffbc47b1183b
I am writing this tutorial mainly to explain how ngentest is written. However, this is also useful for those who want to know how to parse Typescript.
To start, let’s say you have a very simple Typescript file, my.component.ts
import { Component } from '@angular/core';@Component({
selector: 'my',
template: 'hello me.'
})
export class MyComponent {
}
The end goal for this tutorial is to get the following info. from the above code using Typescript parser, which is typescript
itself.
- import info,
Component
,@angular/core
- decorator name,
Component
- class name,
MyComponent
const ts = require('typescript');
const node = ts.createSourceFile(
'x.ts', // fileName
fs.readFileSync('./my.component.ts', 'utf8'), // sourceText
ts.ScriptTarget.Latest // langugeVersion
);
The source file, my.component.ts
, is now parsed using createSoureFile
function, and…