首页 > 解决方案 > Angular SSR - 在浏览器和服务器中使用 performance.now()

问题描述

我想在我的 Angular 组件中设置一些性能标记和度量,以衡量所选组件处理和渲染所需的时间。在“客户端模式”下运行应用程序时它们工作正常,但是一旦我在 SSR 模式下运行应用程序,我就会得到“性能”未定义。

ReferenceError:性能未定义

我尝试从节点“perf_hooks”内部模块导入它,但是当从 app.component.ts 调用时,我得到了未知模块“perf_hooks”。
https://github.com/buggy1985/angular-ssr-performance/blob/HEAD/src/app/app.component.ts#L17

找不到模块“perf_hooks”或其相应的类型声明

如果我在 server.ts 中使用 performance.now() 它似乎正在工作。 https://github.com/buggy1985/angular-ssr-performance/blob/HEAD/server.ts#L13

我可以将性能类从 server.ts 传递给组件吗?让浏览器回退到window.performance?或者我做错了什么?

标签: angularperformancenode-modulesangular-universalbrowser-api

解决方案


我终于设法通过根据平台提供正确的性能api来解决它。

这是我的更改的完整提交: https ://github.com/buggy1985/angular-ssr-performance/commit/39aa08489e589172fa9bce6f1f5588f5eb962337

我基本上创建了一个新的提供程序,它从 server.ts 中的 perf_hooks 注入了导入的性能

import { performance } from 'perf_hooks';
export const PERFORMANCE_API = new InjectionToken('performance-api');
...

@NgModule({
  providers: [
    { provide: PERFORMANCE_API, useValue: performance },
  ],
}

并在 app.browser.module 中注入 windows.performance

providers: [
  { provide: PERFORMANCE_API, useValue: window.performance },
],

在 app.component.ts 中,不是直接使用性能,而是要在构造函数中注入,然后作为 this.performance 使用。

constructor(@Inject(PERFORMANCE_API) private performance) {
    console.log(this.performance.now());
}

推荐阅读