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

Steps for generating an instance of a concrete class using a static method within an abstract class

Trying to instantiate a concrete class from a static method of an abstract class is resulting in the following error: Uncaught TypeError: Object prototype may only be an Object or null: undefined This error occurs on this line in ConcreteClass.js: re ...

Enable the Angular button only when the radio button has been selected

Just starting out with Angular and I have a query. This is a scenario for my project at work. https://i.stack.imgur.com/R3SxA.png In this screenshot, I want to enable the "ajouter" button when at least one radio button is selected in the secure chest (s ...

Creating a model for a different user involves several steps that can be easily

Recently, I have been working on a project involving user interactions such as following other users and viewing their content. Using technologies like Prisma, GraphQL, and Nexus, I decided to create a following model today. The model structure is as follo ...

Comparing strings with data in objects using Angular

all. I have a query. What is the optimal method for comparing data? For instance, if you have a constant response = 225235743; And I aim to locate and exhibit all data in an object with the same ID as the one in this response. This needs to be resolved ...

Encountering a lack of static assets while constructing Superset on a local

My current project involves building Superset locally using docker-compose. One of the steps I took after cloning the repository was to customize the docker-compose.yml file so that it can build images from local source code rather than pulling from Docke ...

Having trouble with my Angular application, seems to be stuck at the loading screen. Not sure what's causing it, possibly

Hey there, I'm hoping to create a straightforward app that showcases posts. However, I've encountered an issue when deploying the initial page which is stuck on "Loading...". I believe it's a minor problem and would appreciate your assistan ...

Extend the express request object with Typescript and then export the modified object

Seeking to enhance the Request object from express with custom fields using typescript. Based on this particular source, I created a file named @types/express/index.d.ts containing the following code : import { MyClass } from "../../src/MyClass" ...

Tips for constructing node.js projects using local versions of the dependencies?

Recently, I've been tackling a rather intricate node.js project (find it at https://github.com/edrlab/thorium-reader/) while trying to incorporate local versions of certain dependencies. Surprisingly, I can successfully build and execute the project ...

What is the best way to implement record updates in a nodejs CRUD application using prisma, express, and typescript?

Seeking to establish a basic API in node js using express and prisma. The schema includes the following model for clients: model Clients { id String @id @default(uuid()) email String @unique name String address String t ...

Guidelines for Managing Test Cases for a Promise-Returning Function with Resolve and Reject in Angular 6

I need to write a test case for a function that returns a Promise with resolve and reject. Here's the function definition: isAuthSuccess(): Promise<any> { const promise = new Promise((resolve, reject) => { if (this.userInfo) { ...

Issue encountered while installing a package with "n low-risk vulnerabilities"

Just set up a new react-native project on big-sur. Encountered an error while trying to install an npm package. How can I resolve this? npm install @react-navigation/native up to date, audited 1026 packages in 2s 6 low severity vulnerabilities To addr ...

Looking for a solution to correct an Enoent error that occurred while trying to install Zurb Foundation for Apps via the command line?

After installing Node.js and updating my $PATH environment, I encountered persistent errors while attempting to install Zurb Foundation for Apps. If anyone has any suggestions on how to resolve this issue, I would greatly appreciate it. Thank you! The com ...

Encountered an error while trying to install reactide: "Module 'vs/editor/contrib/gotoSymbol/goToCommands' cannot be found."

Attempting to set up reactide on a Windows 10 system led to some roadblocks. After cloning the git repository and installing all required dependencies, running the command npm run webpack-production resulted in a series of errors: C:\reactide(3.0-rele ...

Transform a specialized function into a generic function with static typing

First off, I have a network of routes structured like this: interface RouteObject { id: string; path: string; children?: RouteObject[]; } const routeObjects: RouteObject[] = [ { id: 'root', path: '/', children: [ ...

Utilizing npm scripts to pass dynamic arguments seamlessly between different scripts

Is there a way to pass arguments between scripts using npm-run-all for parallel execution? scripts:{ "start":"run-p dev watch -- --theme=$themeId", "dev": "webpack", "watch": "theme watch --en ...

Encountering problems during the installation of Ionic - Error code 'EPROTO'

After attempting to install Ionic on my system, I encountered the following error message: npm ERR! code EPROTO npm ERR! errno EPROTO npm ERR! request to https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz failed, reason: write EPROTO 0:er ...

Where can the PM2 log files typically be found by default?

I'm curious about the default location where PM2 stores its log files. Can anyone point me in the right direction? Currently, I am operating on a Linux Ubuntu 16.04 server and have globally installed PM2 using npm i pm2 -g. ...

React: Unable to locate an index signature with a parameter of type 'string' on type N

While working with a React component, I encountered an issue when trying to access a property from my component state using a key. My editor showed the following warning: Element implicitly has an 'any' type because expression of type 'str ...

Is it necessary to run the npm install command after updating node or npm?

Just curious, do you need to perform an npm install after updating node/npm from version 6.x to 8.x? And if yes, can you shed some light on the reasons behind this practice? I've been struggling to locate relevant information on this topic. ...

encountered an error stating module '@angular/compiler-cli/ngc' could not be located while attempting to execute ng serve

Here is the content of my package.json file: { "name": "cal-euc", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve", "build&qu ...