After installing Angular 10, warnings about optimization for rxjs and lodash CommonJS or AMD dependencies may be displayed

After successfully upgrading my application from Angular 9 to Angular 10, I encountered some warnings when running the ng serve command.

WARNING in src\app\auth\guard\auth.guard.ts depends on 'lodash'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

WARNING in src\app\shared\services\api.service.ts depends on 'rxjs/Observable'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

WARNING in src\app\auth\guard\auth.guard.ts depends on 'rxjs/observable/fromPromise'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

WARNING in src\app\shared\services\localforage.service.ts depends on 'rxjs/observable/forkJoin'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

WARNING in src\app\auth\guard\auth.guard.ts depends on 'rxjs/add/operator/map'. CommonJS or AMD dependencies can cause optimization bailouts.
For more info see: https://angular.io/guide/build#configuring-commonjs-dependencies

Suggestions have been made to whitelist commonJS as a workaround, but this may increase bundle size. How can I resolve the common JS issue while still maintaining an optimized bundle size?

Note: The final code includes the map operator

import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { switchMap, tap, map } from 'rxjs/operators';
import { Observable, from} from 'rxjs';

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {

        return this.getToken().map((token: any) => {
            if ((token !==null) && !this.jwtHelper.isTokenExpired(token.data)) {
               // this.proactiveTokenRefresh(token);
                return true;
            } 
            
            // Store the attempted URL for redirecting
            this.localForage.setItem('redirectUrl', state.url).then(() => {
                // Navigate to the login page
                this.router.navigate(['/login']);
                return false;
            });
        });
}
    
private getToken(): Observable<{}> {
    const token = this.localForage.getItem('id_token');
    
    return from(token);
}`

Answer №1

Here are some helpful reminders from the warnings:

  • Make sure to review all imports from rxjs
import {Observable, fromPromise} from 'rxjs' 
import {map, forkJoin} from 'rxjs/operators'

Remember to properly pipe your operators as shown below:

import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

    import { switchMap, tap, map } from 'rxjs/operators';
    import { Observable, from} from 'rxjs';
    
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    
      return this.getToken().pipe(
        map((token: any) => {
          if ((token !==null) && !this.jwtHelper.isTokenExpired(token.data)) {
            // this.proactiveTokenRefresh(token);
            return true;
          } 
          // Store the attempted URL for redirecting
          this.localForage.setItem('redirectUrl', state.url).then(() => {
            // Navigate to the login page
            this.router.navigate(['/login']);
            return false;
          });
        });
      )
    }
        
    private getToken(): Observable<{}> {
        const token = this.localForage.getItem('id_token');
        
        return from(token);
    }
  • If using lodash, consider replacing lodash functions with available ES2015 functions

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

Navigating within the same URL page in Ionic 5

Hey there, I'm trying to set up a routing system where a page can navigate to the same URL but with different parameters. However, it seems like my routing is working fine for other pages but not for navigating to the exact same URL page. Here's ...

Exploring the Concept of Extending Generic Constraints in TypeScript

I want to create a versatile function that can handle sub-types of a base class and return a promise that resolves to an instance of the specified class. The code snippet below demonstrates my objective: class foo {} class bar extends foo {} const someBar ...

Interacting with Angular 2 Components Inside <router-outlet>

In the header component, there is a search bar. Below that, within the same component, there is a "router-outlet". After pressing enter in the search bar (input field), the search string (event.target.value) should be sent to the component inside the rou ...

Conceal a designated column within a material angular data table based on the condition of a variable

In the morning, I have a question about working with data tables and API consumption. I need to hide a specific column in the table based on a variable value obtained during authentication. Can you suggest a method to achieve this? Here is a snippet of my ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

There seems to be an issue with transitioning the React.js page

I'm currently working on managing the page with react-hook, react-router-dom, and redux. The login functionality has been implemented, and I've written the code to redirect to the main page upon successful login. To achieve this, I utilized hi ...

Using Sass variables within Angular2 components

In my project, I leverage Angular2 and angular-cli. Within the global style.scss file, I have defined several Sass variables. How can I retrieve these variables within my custom components (component.scss)? Should I perhaps import a separate file contain ...

The type 'undefined' cannot be assigned to the type 'string | Buffer | { key: string | Buffer; passphrase: string; } | GetPublicKeyOrSecret'

Verification Code for JWT This function is used to verify a jwt using typescript. public verify( token: string, secretOrPublicKey?: string | Buffer, options?: jwt.VerifyOptions ): Promise<object | string> { if (!secretOrPublicKey) { ...

Encountering a service error that results in the inability to read properties of undefined when passing a method as a

Whenever I attempt to pass a service function as a parameter to another function, an error 'Cannot read properties of undefined myService' occurs during execution. However, calling this.myService.method() individually works perfectly fine without ...

Encountering a 403 error when attempting to upload files from Angular to a Micron

I have encountered an issue while attempting to upload multiple files to the Micronaut Rest API. The uploading process works seamlessly with Postman and Swagger in the Micronaut Rest API, but when using the Angular app, the POST method throws a 403 HTTP er ...

The type '0 | Element | undefined' cannot be assigned to the type 'Element'

I encountered the following error: An error occurred when trying to render: Type '0 | Element | undefined' is not assignable to type 'Element'. Type 'undefined' is not assignable to type 'ReactElement<any, any>&apo ...

Retrieve the part of a displayed element

Presently, I am developing a modal system using React. A button is located in the sidebar and the modal is represented as a div within the body. In the render function of the main component of my application, two components are being rendered: MyModal M ...

Creation of source map for Ionic 2 TypeScript not successful

Struggling with debugging my Ionic 2 application and in need of guidance on how to include souceMap for each typescript file that corresponds to the javascript files. Despite enabling "sourceMap":true in my tsconfig.json file, the dev tools in Chrome do n ...

Navigating Angular: Efficient Ways to Manage API Requests

As a newcomer to signals, I've been exploring their usage more within our application. However, one area that still confuses me is the relationship between rxJS and Signals. Due to our use of Angular's HTTP client, we work with observables, which ...

Tips for duplicating chosen documents utilizing AngularCLI in conjunction with WebPack for the production build

I am facing an issue with my Angular2 app when building it for production using Angular CLI and WebPack. In order to deploy the app to our production server (IIS), I need to copy certain files to the dist folder. Specifically, I require the web.config and ...

Tips for writing an async function using TypeScript

I've been working with Typescript and NLP.js. However, I'm encountering an issue where the argument manager is displaying 'Parameter manager implicitly has an any type'. I attempted to use :, but it didn't solve the problem eff ...

The sequence of output in TypeScript when using Gulp is similar to running tsc with a tsconfig

After setting up a tsconfig file and successfully running the command-line tsc, I encountered an issue when using gulp-typescript with a tsconfig.json and outFile specified. The output ordering was different, and I have been unable to find a solution in Gu ...

Obtaining the IP address upon page load in Angular 4: A step-by-step guide

In the midst of my Angular4 project, I'm on a mission to fetch the system IP address upon page load and send it over to the API for storage in a MSSQL database. However, each time the page loads, two rows are inserted and the IP address is coming up a ...

Enhance constructor functionality in Ionic 4 by incorporating additional parameters

Recently, I started using Ionic and came across a location page. In the location/location.page.ts file, there was an automatically generated empty constructor like this: constructor() { } Initially, the page functioned properly with this setup. However, ...

What is the best way to set up an endpoint in Angular for image uploading?

Using the Kolkov Angular editor in my Angular application, I have successfully created a rich text editor. Currently, I am looking to upload images from the editor to the server. I already have a function in place that takes a file as an argument and send ...