Objective
I am aiming to distribute a TypeScript module augmentation of RxJS as an npm package for usage in Angular projects.
Challenge
While the package functions correctly in local development mode within an Angular application, it fails to import properly once the app is built for production.
Specifics
The main addition is a new method: Observable.safeSubscribe()
(detailed source code available here: ngx-safe-subscribe.ts)import { Observable, Subscription } from 'rxjs'; declare module 'rxjs/internal/Observable' { interface Observable<T> { safeSubscribe: typeof safeSubscribe; } } export function safeSubscribe<T>(...): Subscription { ... } Observable.prototype.safeSubscribe = safeSubscribe;
The package was created using ng-packagr
Upon importing and utilizing the package in an Angular project, everything works smoothly:
(see complete demonstration here: demo)import { Component, OnDestroy } from '@angular/core'; import { of } from 'rxjs'; import '@badisi/ngx-safe-subscribe'; @Component({ selector: 'my-app', templateUrl: './app.component.html' }) export class AppComponent implements OnDestroy { constructor() { of([]).safeSubscribe(this, () => { console.log('ok'); }); } ngOnDestroy(): void {} }
However, upon building for production, the package fails to be imported in the final distribution:
ng serve --prod [error in console]: TypeError: Object(...)(...).safeSubscribe is not a function
I have tried with all the latest versions available
<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9c8c7cedcc5c8dbe99e87998799">[email protected]</a>, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="186c61187d6b7b6a71686c582b3629362b">[email protected]</a>, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c626b217c6d6f676d6b7e4c382238223c">[email protected]</a>
Additionally, using the named import style in Visual Studio Code results in the following message:
import { safeSubscribe } from '@badisi/ngx-safe-subscribe'; [ts] 'safeSubscribe' is declared but its value is never read.
The root cause could be related to TypeScript, Angular CLI, Webpack, or ng-packagr's inability to recognize the augmentation and import it correctly into the final distribution.
Any assistance on this matter would be greatly appreciated! Thank you.