Why do I keep encountering the error "global is not defined" when using Angular with amazon-cognito-identity-js?

To start, run these commands in the command line:

ng new sandbox
cd .\sandbox\
ng serve

Now, navigate to http://localhost:4200/. The application should be up and running.

npm install --save amazon-cognito-identity-js

In the file

\src\app\sign-up\sign-up.component.ts
, include this line of code:

import * as AmazonCognitoIdentity from 'amazon-cognito-identity-js';

Add a constructor function:

  constructor() {
    new AmazonCognitoIdentity.CognitoUserPool({});
  }

Refresh http://localhost:4200/.

If the page is blank and you encounter a console error that says:

Uncaught ReferenceError: global is not defined
    at Object../node_modules/buffer/index.js (index.js:43)
    at __webpack_require__ (bootstrap:76)
    at Object../node_modules/amazon-cognito-identity-js/es/AuthenticationHelper.js (AuthenticationHelper.js:1)
    at __webpack_require__ (bootstrap:76)
    at Object../node_modules/amazon-cognito-identity-js/es/index.js (index.js:1)
    at __webpack_require__ (bootstrap:76)
    at Object../src/app/app.component.ts (main.js:94)
    at __webpack_require__ (bootstrap:76)
    at Object../src/app/app.module.ts (app.component.ts:9)
    at __webpack_require__ (bootstrap:76)

What steps would you recommend to fix this error?

Answer №1

Ensure to include the following code snippet as the final line in the /src/polyfills.ts

(window as any).global = window

Answer №3

If you are currently utilizing Angular versions above 15, please note that the polyfills.ts file is no longer present in the default Angular project setup. To address this, you can create your own polyfills file with a custom name and store it in any preferred folder (e.g., src/crossbrowsers/my-custom-polyfills.ts).

Subsequently, include this newly created polyfills file in the following locations:

  1. Angular.json file within the "polyfills" arrays (located under project/smart/architect/build/options/polyfills and project/smart/architect/test/options/polyfills [for tests]).

The configuration would resemble the following structure:

project/smart/architect/build/options/polyfills

"options": {
            "outputPath": "dist/smart",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": [
              "zone.js",
              "src/crossbrowsers/my-custom-polyfills.ts"
            ],
          ...
          } ...

project/smart/architect/test/options/polyfills

"test": {
      "builder": "@angular-devkit/build-angular:karma",
      "options": {
        "polyfills": [
          "zone.js",
          "zone.js/testing",
          "src/crossbrowsers/my-custom-polyfills.ts"
        ],
        ...
       } ...
  1. tsconfig.app.json file

Add the path to your custom polyfills file within the "files" array in this file. The setup should look similar to:

...
"files": [
    "src/main.ts",
    "src/crossbrowsers/my-custom-polyfills.ts"
  ],
...

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

TypeScript application was constructed with incorrect imports from the src folder instead of the dist folder

Summary: App successfully built but importing files from src folder instead of dist I have a TypeScript-powered Express application. This is the configuration of tsconfig.json file: { "compilerOptions": { "target": "es5&quo ...

Discovering the JavaScript source file for a package using WebStorm and TypeScript

In my TypeScript project, there is a usage of Express with the following method: response.send('Hello'); I am interested in exploring the implementation of the send() method. However, when I try to navigate to the source code by ctrl+clicking o ...

``If you're looking to integrate a 360-degree product viewer into your Angular application, here is a

I am in need of showcasing a 360 Product viewer consisting of an array of 36 car images in base64 format. Despite attempting to utilize the angular-three-sixty Package by @mediaman, I was only met with an empty canvas. Does anyone have experience in implem ...

Converting a TypeScript object into a JSON string

When working with TypeScript, I am facing a challenge while trying to initialize an object that requires a JSON string for the "options" parameter. Specifically, it pertains to the object mentioned here. It is crucial that the options parameter be in JSON ...

I am experiencing an issue with the PUT method on my API as it is not correctly setting the req.body data

Below is the code snippet for implementing the PUT method: [/api/[id].ts] case "PUT": try { const user = await UserModel.findOneAndUpdate( { _id: id, }, { $set: req.body, ...

Utilize the <wbr> tag within FormattedMessage and assign it as a value while coding with TypeScript

Trying out the optional word break tag <wbr> in a message within <FormattedMessage id="some:message" />. Context Some words or texts are too lengthy for certain parent elements on smaller mobile screens, and we have a column layout t ...

Creating a Custom Form Control in Angular 2 and Implementing Disable Feature

I have developed a unique custom control using ControlValueAccessor that combines an input[type=text] with a datepicker. While the template-driven forms accept it without any issues, the situation changes when implementing the model-driven approach (react ...

What steps should I take to successfully compile my Typescript Webpack project without any errors?

Currently, I am attempting to convert only two .js files into .ts files within my webpack node.js project and then compile them (actions.ts and flux.ts). When I execute the command: webpack --progress --colors I encounter the following errors: 'use ...

Angular: encountering template parse errors with unknown <component> element

I'm struggling to import a component into another component, but the imported component cannot be found. Here is the error message: Uncaught Error: Template parse errors: 'aktenkorrespondenzenTemplate' is not a known element: 1. If 'ak ...

What is the best way to connect my Typescript NextJS code to my Express API?

My goal is to extract data from my API, which is providing the following JSON: [ { project: "Challenges_jschallenger.com" }, { project: "Using-Studio-Ghilis-API-With-JS-Only" }, { project: "my-portfolio-next" }, { proj ...

Creating Awesome Icons in Kendo Grid with Code In this tutorial, we will learn how to programm

Looking to have a Kendo grid display a green fas-fa-clock icon if isActive is true, and a grey far-fa-clock icon if false. Clicking on the icon should toggle between true and false. Currently, the grid just shows the word true or false in the column. Cod ...

Using ngOnChange on a FormGroup in Angular

Is there a way to detect real-time changes in the fields of a FormGroup? My component structure consists of a simple parent-child setup: Parent Component View <my-child [myForm]="myForm"></my-child> Child Component Controller @Input() myFor ...

In Typescript, we can streamline this code by assigning a default value of `true` to `this.active` if `data.active

I am curious if there is a better way to write the statement mentioned in the title. Could it be improved with this.active = data.active || true? ...

There has been an error of type TypeError, as the property 'replace' cannot be read from a null value

I encountered a TypeError message, even though my application seems to be functioning properly. "ERROR TypeError: Cannot read property 'replace' of null" I'm struggling to understand how to fix this issue. Can someone provide me ...

When working with Angular/Typescript, the error message "compilation of 'export const' is not possible

Embarking on creating my very own Angular library, I took the first step by adding a service without any issues. The challenge arose when I decided to move a constant to a file named tokens.ts for the service to reference. Following this change, the build ...

Adding the activateRoute class to Angular for enhanced functionality

My question pertains to a specific section in the book pro-Angular-6, where I encountered the following syntax: constructor(private model:Model,activatedRoute:ActivatedRoute) {} I am unsure about the following aspects: How can we use a class without i ...

What are some strategies for accessing the original values of form components that have not been altered when using ngModel?

I am currently developing a form and I intend to utilize the previous values as "value" in the form. By employing ngModel dynamically, I am able to change some properties. However, I have encountered an issue where the field that remains unchanged by the u ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

Increasing the number of service providers in Angular2-4 directives

Is there a way to apply both * to a string? Below is the code snippet I am working with: <a class="sidenav-anchor" *ngIf="!item.hasSubItems()" md-list-item md-ripple [routerLink]="[item.route]" routerLinkActive="active" [routerLinkActiveOptions]="{ex ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...