【问题标题】:Angular 9 SSR Build Serve eror -- ERROR ReferenceError: document is not definedAngular 9 SSR Build Serve eror - ERROR ReferenceError: document is not defined
【发布时间】:2020-03-11 12:40:52
【问题描述】:

ERROR ReferenceError: 文档未定义

import { readFileSync } from 'fs';
const domino = require('domino');  // import the library `domino`
const DIST_FOLDER = join(process.cwd(), 'dist/browser');
const template = readFileSync(join(DIST_FOLDER, 'index.html')).toString(); // use `index.html` as template
const win = domino.createWindow(template); // create object Window
global['window'] = win;
global['Event'] = win.Event;               // assign the `win.Event` to prop `Event`
global['document'] = win.document;

即使在 Server.ts 修复问题中添加这个,但在性能 TTFB 时间太高。 有没有解决方案...?

【问题讨论】:

  • 你的 TTFB 有多长?
  • 我遇到了同样的错误。你有解决办法吗?

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


【解决方案1】:

尝试使用 @angular/common 包提供的 DOCUMENT 常量

import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable()
export class MyService {
  constructor(@Inject(DOCUMENT) private document: Document) {}
}

【讨论】:

  • 当访问这个文档时,文档就足够了,或者你需要用 this.document 替换它,因为它变成了一个局部变量?
  • 使用this.document 请看angular.io/guide/dependency-injection-in-action 注入localStorage时,作为this.storage.getItem(key)使用
【解决方案2】:

这些全局变量包括 window、document、localStorage、indexedDB、setTimeout 和 setInterval 你不能在 Angular 通用应用程序中使用

使用来自 Anguar 通用模块的文档对象

从库中导入

import { DOCUMENT } from '@angular/common';

在服务中注入

@Inject(DOCUMENT) private document: Document,

【讨论】:

    【解决方案3】:

    尽管有它的标题,但看起来您的问题更多是关于慢速 TTFB,而不是 document 未定义的错误。

    关于未定义的文档错误,解决方法是:

    • 如果错误出现在自己的代码中,请使用以下注入@Inject(DOCUMENT) private document

    • 如果错误出现在 3rd 方库中,如果您无法将这些库替换为其他适用于 Angular Universal 的库,请使用 domino

    要解决缓慢的 TTFB,没有神奇的解决方案。尽量避免渲染不需要在服务器端渲染的组件,确保没有长时间运行的 API 调用,使用缓存

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 2018-11-20
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2020-12-09
      • 1970-01-01
      相关资源
      最近更新 更多