Tuesday, August 20, 2019

Debug Angular library project's typescript code from root application project

Option 1:

The below steps can be used to debug typescript in Angular library project with Angular 8.*

1. Create Angular app
ng new myappwithlib

2. Create library project
ng generate library ui-uploadfile-lib

3. be sure both library and app project build
ng build ui-uploadfile-lib
ng serve

4. update library project to expose some function from library typescript code
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'lib-ui-uploadfile-lib',
template: `
<p>
Load library: {{this.libraryTitle}}
</p>
`,
styles: []
})
export class UiUploadfileLibComponent implements OnInit {
libraryTitle = "my ibrary title";
constructor() { }
ngOnInit() {
}
}
5. import library module to app module file
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {UiUploadfileLibModule} from 'ui-uploadfile-lib'
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
UiUploadfileLibModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

6. (Important) in application's root folder, update angular.json file's application serve setting (not library project's build settings) as below
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"sourceMap": {
"scripts": true,
"styles": true,
"vendor": true
},
"browserTarget": "myappwithlib:build"
},
"configurations": {
"production": {
"browserTarget": "myappwithlib:build:production"
}
}
},
7. start app by executing 
ng serve

In browser's javascript debugger page as shown below. Depends on project settings, the typescript code may also show up in localhost:4200/ng: section, so be sure to search the source tree to try to locate the typescript code.



6. Options 2
If you only need to debug some javascript/typescript code from a third party npm package, and do not need to maintain the code, then there is also another easy and quick way to do so. Just copy the source code from the third party package into the src folder of your angular project, and then search and replace all import statement in your js/ts files so as to import the third party package's classes and modules from the local copy of the source files. 

You can leave the project's package.json as it is, the downloaded package will just be ignored.

1 comment: