9

升级到 Angular 9 后,ReferenceError: window is not defined运行时出现错误yarn serve:ssr

在我们的 Angular 应用程序中,我们使用 Domino 的技巧来模拟 SSR 的窗口(如在https://github.com/Angular-RU/angular-universal-starter/blob/master/server.ts#L21中)。

因此,在ng update我在导入后添加了这些行之后server.ts


const distFolder = join(process.cwd(), 'dist/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';

// Emulate browser APIs
const domino = require('domino');
const fs = require('fs');
const templateA = fs.readFileSync(join(distFolder, indexHtml)).toString();

const win = domino.createWindow(templateA);
win.Object = Object;
win.Math = Math;
global['window'] = win;
global['document'] = win.document;

但是,似乎设置global['window']发生得太晚或永远不会发生。

您知道在哪里设置global['window']以便角度组件和库可以在 SSR 中访问它吗?

4

3 回答 3

2

解决了,感谢这条评论https://github.com/angular/universal/issues/1678#issuecomment-627031128

关键是要有线

import { AppServerModule } from './src/main.server';

定义之后global['window']

注意编辑器中的自动格式化程序,它通常会自动将导入行放在文件顶部:)

于 2020-05-13T21:16:58.377 回答
0

I put it below the imports and above the app() method


import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';

import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync, readFileSync } from 'fs';
import * as domino from 'domino';
import * as core from 'express-serve-static-core';


const template = join('browser', 'index.html');
const win = domino.createWindow(template);

global['window'] = win;
global['document'] = win.document;

// The Express app is exported so that it can be used by serverless Functions.
export function app(): core.Express {
于 2020-02-13T16:28:34.803 回答
0

我做了两个任务来修复它。

首先 - 在 angular.json 中设置“优化”:服务器构建为 false,它有助于找到 3d paty 模块所谓的错误

第二 - 我在我的 server.ts 中向上移动多米诺骨牌

于 2020-03-19T08:47:32.183 回答