Get Angular 2 .ts files instead of .d.ts files

2020-03-22 07:08发布

问题:

When I work with angular2 code I often need to see the implementation of a class, let's say the Router class.

If I click on the Router type in my IDE WebStorm, e. g. inside the constructor of another class

export class myClass {
    constructor(private router: Router) {}
    // ...
}

my IDE takes me to the TypeScript definition file router.d.ts inside my node_modules folder. What I want is it to take me to the original router.ts file with the implementation of the router class, not just its definition.

The original .ts file is not included in the node_modules folder structure when you get angular2 from github via the standard package.json suggested in the Angular2 Quickstart. Currently, I have to look up the original code in the official github repo.

Any ideas how to get the .ts files into my node_modules/@angular folder instead of the .d.ts files?

回答1:

Sadly, it's not possible since no TS files exist. Even if you add them it still not possible since you import real angular paths which always point to the definition files. On top of that the file structure of the project does not correlate to the structure of the import string literals.

Some background and more information

The NPM package does not include .ts files, this is by design from the angular team. Up until some time ago the .ts files were indeed supplied with the NPM package.

The reasoning for removing them is to disable abuse from users accessing private classes and @internal and private APIs which is public methods/properties in the API that are not supposed to be public but must be so other angular internal classes can use them.

We used to see a lot of code samples out there doing things like import { PromiseCompleter } from 'angular2/src/facade/lang'; (before RC0) but this was changed when the project structure had a big structure refactor in RC0. This abuse was wide and it's bad, very bad... For users and for Angular PR.

The Angular project has a complex and robust build process where all of the API is moved from .ts files into d.ts files using an automated process that limits exposure. (public_api_guard)

The end result is d.ts files only.

It's also not possible to clone the git repo and use it since, again, the file structure is way way different so imports will have to change. Most importantly without the build Angular will, most likely, not work.

A solution using a different approach

However, if you debug your app you notice that you reach actual angular core .ts files in the source view of the console, this is because the NPM package comes with source map files that include the whole TS source code. Nice trick they did there.

This is what I use to dig deep into angular, it works quite great and I get a lot from it. It's not as nice as Goto Declaration but it something... IMO it's also easier to understand when you step through code...