全局、缓冲和过程在离子4角8中是未定义的



我正试图在Angular 8 ionic 4应用程序中使用外部js-npm库,我收到了

ERROR Error: Uncaught (in promise): ReferenceError: global is not defined

我试图通过在polyfill.ts中插入以下代码来解决这个问题:

(window as any).global = window;
import * as buffer from 'buffer';
window['buffer'] = buffer;
import * as process from 'process';
window['process'] = process;

当我尝试用"离子服务"运行离子应用程序时,我收到一个运行时错误:

index.js:43 Uncaught ReferenceError: global is not defined
at Object../node_modules/node-libs-browser/node_modules/buffer/index.js (index.js:43)
at __webpack_require__ (bootstrap:84)
at Module../src/polyfills.ts (polyfills.ts:1)
at __webpack_require__ (bootstrap:84)
at Object.1 (zone-flags.ts:5)
at __webpack_require__ (bootstrap:84)
at checkDeferredModules (bootstrap:45)
at Array.webpackJsonpCallback [as push] (bootstrap:32)
at polyfills.js:1
...
ERROR Error: Uncaught (in promise): ReferenceError: global is not defined
ReferenceError: global is not defined
at Object../node_modules/stream-http/lib/capability.js (capability.js:1)
at __webpack_require__ (bootstrap:84)
at Object../node_modules/stream-http/lib/request.js (request.js:1)
at __webpack_require__ (bootstrap:84)
at Object../node_modules/stream-http/index.js (index.js:1)
at __webpack_require__ (bootstrap:84)
at Object../node_modules/rss-parser/lib/parser.js (parser.js:2)
at __webpack_require__ (bootstrap:84)
at Object../node_modules/rss-parser/index.js (index.js:3)
at __webpack_require__ (bootstrap:84)
at resolvePromise (zone-evergreen.js:797)
at resolvePromise (zone-evergreen.js:754)
at zone-evergreen.js:858
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:34182)
at ZoneDelegate.invokeTask (zone-evergreen.js:390)
at Zone.runTask (zone-evergreen.js:168)
at drainMicroTaskQueue (zone-evergreen.js:559)

有什么建议吗?

原始答案

Angular是一个面向客户端的框架。运行时目标是浏览器。您不能在那里使用像process这样的库,因为这些库只有在运行nodejs进程时才可用。

您很可能希望将应用程序拆分为客户端和服务器端。

rss解析器的解决方案

正如你在评论中提到的,有问题的库是rss-parser。如本期所述,rss-parser目前在使用捆扎机时无法正确处理角度。很可能是由于没有ES模块支持。

解决方案是使用库附带的预绑定版本。要做到这一点,请将预打包版本添加到您的angular.json,添加到architectsbuild部分的script数组中。RSSReader现在在您的window对象中全局可用,可以这样使用:

import { Component } from '@angular/core';
// This tells TypeScript that you know this will be available globally during runtime.
// Unfortunately, RSSParser has no TS Declarations, so you have to use any or make a more concrete type yourself
declare const RSSParser:any;
@Component({
selector: 'my-app',
templateUrl: './app.component.html', 
styleUrls: [ './app.component.css' ]
})   
export class AppComponent  {
title:string = '';
items:Array<any> = []; 
constructor() {
const CORS_PROXY = "https://cors-anywhere.herokuapp.com/" 
let parser = new RSSParser(); 
parser.parseURL(CORS_PROXY + 'https://www.reddit.com/.rss', (err, feed) => {
if (err) throw err;
console.log(feed);
this.title = feed.title;
this.items = feed.items;
})
}
}

这是一个正在工作的Stacklitz。

最新更新