Angular production application is experiencing issues due to a missing NPM package import

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.

Answer №1

Have you attempted running ng serve --prod or ng build --prod?

Answer №2

After some perseverance, I managed to discover the solution myself.

Here's a quick fix:

To resolve the issue, add the following property to your npm package:

package.json {
    sideEffects: true
} 

A Closer Look

The problem stemmed from ng-packagr, which sets sideEffects:false in the distribution version of the package.json file.

This setting is recommended by the Angular Package Format v6 for optimizing bundle distribution:

"Packages with this property set to false will undergo more aggressive processing by webpack compared to those without. As a result, these optimizations lead to a smaller bundle size and improved code distribution across chunks after splitting." [source]

By setting sideEffects to false, only the actual utilized code will be bundled. However, in my case, the enhancement was labeled as "declared but never read", causing it to be disregarded during the build process. With sideEffects set to true, webpack will bundle the entire package without question.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to include a Web Service within an export variable in Angular 2 using TypeScript?

Is there a way to incorporate JSON data retrieved from the server into the export var HEROES: Hero[ ] function? Here is the link: https://angular.io/resources/live-examples/toh-5/ts/eplnkr.html In app/mock-heroes.ts, you will find the following data, im ...

A guide to using Angular to emphasize text based on specific conditions met

Currently, I am developing a testing application that requires users to choose radio type values for each question. The goal is to compare the selected answers with the correct answers stored in a JSON file. To achieve this, I have implemented an if-else ...

When the button is clicked, (ngSubmit) will be triggered

In my Angular2 Form Component, I have implemented two buttons with different functionalities. Button Submit: This button submits all the values to the API. Button Add: This button adds an object to an array. Here are the two methods: onSubmit() { this. ...

Best practices for effectively managing interface design

My current interface looks like this: export interface Folder { name: string; id: number; date: Date; } However, in the actual scenario, the JSON response provides the date as a string type. How should I handle this data transfer between the back-en ...

Updating npm dependencies with unmet peer requirements

Having trouble updating react-router-dom, encountering an ERR with the error message ERESOLVE unable to resolve dependency tree. Attempting to update using the command: npm update "popper.js" "bootstrap" "react-router-dom" Could not resolve dependency: np ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Employing a provider within a different provider and reciprocally intertwining their functions

I'm currently facing an issue with two providers, which I have injected through the constructor. Here's the code for my user-data.ts file: @Injectable() export class UserDataProvider { constructor(private apiService: ApiServiceProvider) { ...

Ways to resolve the issue: "internal/modules/cjs/loader.js:638 throw err; ^"

I am encountering an error when trying to run my Vue.js project using npm on localhost:8080. Is there a solution to resolve this issue? This error specifically occurs when I attempt to install node_modules and package-lock.json in my Vue folder, which inc ...

Angular offers a range of search filters for optimizing search results

The system currently has 3 search fields: 1. Name.... 2. Subject.... 3.Price.... Each of these filters works independently - when searching by name, only results matching that name are displayed; similarly for subject and price. However, the challeng ...

Updates to TypeScript 2.3.1 creating disruptions in SystemJS plunk

Check out this official Angular + TypeScript plunk using SystemJS 0.19.31, now updated to TypeScript 2.3.0. However, changing the SystemJS configuration in the same plunk to TypeScript 2.3.1 or 2.3.2 'typescript': 'npm:<a href="/cdn-cgi ...

Encountering an issue while trying to run npm init and the

I am encountering an issue while trying to set up NPM in my project. Every time I attempt to initialize it, I get the following error: C:\Users\work-\Documents\MyWork\Folder\utils>npm init npm ERR! code MODULE_NOT_FOUND npm ...

Having trouble installing Popper.js?

I have encountered an issue while attempting to install popper.js in my angular project. ng new <<project>> cd <<project>> npm install popper --save npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules&b ...

After calling the service, Angular 2 is unable to perform any actions within the subscribe method

I am struggling with what to do after authenticating my user. Once I receive the data, I want to redirect them to the appropriate page based on their role and display their name on that page. I have tried various methods, but it seems like when I try to ca ...

Unable to set up Angular 1.5 component router

Struggling to incorporate the Angular 1.5 component router into a new project has been quite challenging for me. According to the instructions provided at https://docs.angularjs.org/guide/component-router, running the following command should do the trick: ...

Revising Vue for lazy loading upgrades

Facing a challenge in optimizing the lazy loading of components in my application. I aim to display a loading spinner while any component is being loaded, as well as handling errors with the same approach, resulting in redundant code. export default c ...

Guide on utilizing mat-slide-toggle to assign either a value of 1 or 0

I am utilizing the mat-slide-toggle feature from Material in a similar manner to this example https://material.angular.io/components/slide-toggle/overview The problem I am encountering is similar to the issue outlined in this link: https://stackblitz.com ...

Update a value in the sessionStorage using Angular

I am working on a function that handles checkbox options based on event.target.name. The goal is to add the checkbox option to session storage if it's not already there, and update the value if it exists. However, I'm facing some issues with my c ...

Incorporating telepat-io into a Java Struts enterprise solution

Our J2EE enterprise application, built on Java Struts, has a static front end. Our team's architect has opted to enhance the user authentication by incorporating Ajax and JavaScript functionalities using telepat-io. The project is currently managed w ...

Run your NPM start script on any operating system

I am working on an Electron application that needs to be compatible with both Windows and OS X. I am trying to develop a cross-platform start script, but so far I have not been successful. The main issue seems to be setting the NODE_ENV environment variabl ...

Having trouble installing the @aws-amplify/cli package with npm?

Just getting started with this, I'm attempting to set up aws amplify using the command line but I keep encountering error messages. I've tried using sudo and taking the safe route but nothing seems to work. I am new to node.js and understanding d ...