Angular + amazon-cognito-identity-js,为什么我得到错误:全局未定义



从命令行:

ng new sandbox
cd .sandbox
ng serve

打开 http://localhost:4200/。它有效。

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

srcappsign-upsign-up.component.ts里面添加以下代码行:

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

添加构造函数:

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

刷新 http://localhost:4200/。

页面为空白。存在控制台错误:

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)

解决此错误的最佳方法是什么?

把它作为/src/polyfills.ts的最后一行

(window as any).global = window

我一直在研究这个问题,我能够按照以下链接修复:https://github.com/aws-amplify/amplify-js/issues/678#issuecomment-384260863

if (全局 === 未定义( { var 全局 = 窗口; }

如果有人正在阅读本文并使用 Angular>15 (cf: https://angular.io/guide/browser-support#polyfills(,由于 polyfills.ts 在默认的角度项目中不再存在,您可以根据需要创建命名并将其放在您想要的文件夹下(例如:src/crossbrowsers/my-custom-polyfills.ts(

然后将其添加到:

  1. Angular.json 文件 在"polyfills"数组中(在project/smart/architect/build/options/polyfills和Project/smart/architect/test/options/polyfills下[用于测试](

你会有类似的东西:

项目/智能/架构师/构建/选项/填充物

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

项目/智能/架构师/测试/选项/填充

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

在文件数组中。 你会有这样的东西:

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

最新更新