【问题标题】:Angular SSR with Nrwl/Nx - external library calls document.getElementById带有 Nrwl/Nx 的 Angular SSR - 外部库调用 document.getElementById
【发布时间】:2019-12-20 14:36:55
【问题描述】:

在当前项目中,我正在 Nrwl/Nx 工作区上实现 Angular 服务器端渲染。我严格按照 Nrwl 的这些guidelines。在运行节点应用程序之前一切正常。该项目包含一个名为 Plotly.js 的外部库,不幸的是它使用了document。它抛出以下错误

/Users/PATHTOPROJECT/node_modules/plotly.js/dist/plotly.js:105975
    var style = document.getElementById(id);
                ^
ReferenceError: document is not defined

Plotly.js 被导入到延迟加载的 NgModule 中

import * as PlotlyJS from 'plotly.js/dist/plotly.js';
import { PlotlyModule } from 'angular-plotly.js';
PlotlyModule.plotlyjs = PlotlyJS;

当然,在 SSR 中,document 不可用。 Plotly.js 仅用于延迟加载的路由。我试图保护这条路线只能在isPlatformBrowser 上使用,但这并不能解决问题。也许有可能添加一个“假”document 或类似的东西?

你有什么想法吗?谢谢和欢呼!

【问题讨论】:

  • 你在哪里包含/使用 plotly.js?
  • 你试过ngAfterViewInit() 吗?

标签: angular plotly server-side-rendering angular-universal


【解决方案1】:

您最需要的是:https://github.com/angular/angular/blob/9b9116c79d626b6356f3dfe0d48c9d990ac412a2/packages/platform-browser/src/browser.ts#L100

但我经验不足,无法向您展示如何制作自定义 BrowserModule.withServerTransition() 您可以阅读文档并自行尝试。

这里有解决方案如何使用ngAfterViewInit() 将库导入组件:https://stackoverflow.com/a/51150552/6310260

因为你想操纵样式。这是它在 SSR 上工作的一种方式:

模板:

<div [ngStyle]="setStyle(item.img)"></div>

component.ts

setStyle(imgUrl: string) {
    return {
      'background-image': `url('${imgUrl}')`,
      'background-position': 'center',
      'background-repeat': 'no-repeat',
      'background-size': 'cover'
    }
  }

第二个:试试“lifecycle-hook”ngAfterViewInit()

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 2020-08-29
    • 2019-04-15
    • 2019-11-10
    • 2018-08-14
    • 2020-02-05
    • 1970-01-01
    • 2018-10-30
    • 2021-11-15
    相关资源
    最近更新 更多