Angular 9 SSR构建服务错误-错误ReferenceError:未定义文档

时间:2020-03-11 12:40:52

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

错误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时间过长。 有解决办法吗...?

3 个答案:

答案 0 :(得分:2)

这些全局变量包括窗口,文档,localStorage,indexedDB,setTimeout和setInterval,您不能在角度通用应用程序中使用

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

从图书馆导入

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

注入服务

@Inject(DOCUMENT) private document: Document,

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:0)

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

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

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

  • 如果错误不能在第三方库中显示,请使用domino,如果您无法将这些库替换为其他可用于角度通用的库。

要解决缓慢的TTFB,没有魔术解决方案。尽量避免呈现不需要在服务器端呈现的组件,请确保您没有长时间运行的API调用,请使用缓存