Angular 9 SSR Build Serve eror -- ERROR ReferenceError: document is not defined
Angular 9 SSR Build Serve eror -- ERROR ReferenceError: document is not defined
错误引用错误:文档未定义
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 时间太长。
有解决办法吗...?
这些全局变量包括 window、document、localStorage、indexedDB、setTimeout 和 setInterval 是你不能在 angular 通用应用
中使用的
使用 Anguar 通用模块中的文档对象
从库中导入
import { DOCUMENT } from '@angular/common';
在服务中注入
@Inject(DOCUMENT) private document: Document,
尝试使用@angular/common包提供的DOCUMENT常量
import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Injectable()
export class MyService {
constructor(@Inject(DOCUMENT) private document: Document) {}
}
尽管标题如此,但看起来您的问题更多是关于慢速 TTFB,而不是 document
未定义的错误。
关于那个undefined document错误,解决方法是:
使用下面的注入@Inject(DOCUMENT) private document
如果错误出现在你自己的代码中
如果错误出现在第 3 方库中,如果您不能将这些库替换为其他适用于 angular 通用库的库,请使用 domino
。
解决TTFB慢,没有什么灵丹妙药。尽量避免渲染不需要在服务器端渲染的组件,确保你没有长时间的 运行 API 调用,使用缓存
错误引用错误:文档未定义
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 时间太长。 有解决办法吗...?
这些全局变量包括 window、document、localStorage、indexedDB、setTimeout 和 setInterval 是你不能在 angular 通用应用
中使用的使用 Anguar 通用模块中的文档对象
从库中导入
import { DOCUMENT } from '@angular/common';
在服务中注入
@Inject(DOCUMENT) private document: Document,
尝试使用@angular/common包提供的DOCUMENT常量
import { Inject, Injectable } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Injectable()
export class MyService {
constructor(@Inject(DOCUMENT) private document: Document) {}
}
尽管标题如此,但看起来您的问题更多是关于慢速 TTFB,而不是 document
未定义的错误。
关于那个undefined document错误,解决方法是:
使用下面的注入
@Inject(DOCUMENT) private document
如果错误出现在你自己的代码中如果错误出现在第 3 方库中,如果您不能将这些库替换为其他适用于 angular 通用库的库,请使用
domino
。
解决TTFB慢,没有什么灵丹妙药。尽量避免渲染不需要在服务器端渲染的组件,确保你没有长时间的 运行 API 调用,使用缓存