【问题标题】:Angular Universal error ReferenceError: MouseEvent is not definedAngular Universal 错误 ReferenceError:未定义 MouseEvent
【发布时间】:2020-02-15 04:03:31
【问题描述】:

我正在使用 Angular Universal 渲染 ssr,同时使用 Angular cli 命令:npm run build:ssr && npm run serve:ssr,我收到错误。

使用 Angular8

/home/xyz/projects/my-app/dist/server/main.js:139925
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__metadata"])("design:paramtypes", [MouseEvent, HTMLElement]),
                                                                               ^

ReferenceError: MouseEvent is not defined
    at Module.UPO+ (/home/xyz/projects/my-app/dist/server/main.js:139925:84)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! patient-app@0.0.0 serve:ssr: `node dist/server`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the patient-app@0.0.0 serve:ssr script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/vijay/.npm/_logs/2019-10-18T07_30_11_791Z-debug.log

【问题讨论】:

    标签: javascript node.js angular typescript runtime-error


    【解决方案1】:

    DocumentWindowlocalstorageMouseEvent 等客户端代码在 Angular 应用程序的通用模式下运行时将不存在,因为您的第一页将在服务器上呈现。

    因此,如果您的代码中存在任何此类代码,那么您需要像这样将您的客户端代码包装在 platformBrowser 中 -

    import { ..., PLATFORM_ID, ... } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    
    
    constructor(
        @Inject(PLATFORM_ID) private platformId: Object,
    ){
        if (isPlatformBrowser(this.platformId)) {
           // MouseEvent code
        }
    }
    

    【讨论】:

    • 无论您在哪里使用过mouse 事件或任何客户端事件。
    • 当我们使用 localstorage 时,错误会说 localstorage 还是仍然会说 Mouse event?
    • 它会说 localstorage。
    • 这个解决方案对我不起作用。还是一样的例外。
    猜你喜欢
    • 1970-01-01
    • 2017-01-02
    • 2020-11-12
    • 2020-08-05
    • 2020-05-28
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多