JS注解怎么标注性能监控_ 性能埋点与监控函数的JS注解使用说明

通过装饰器模拟注解实现JS性能监控,使用@performanceMonitor记录函数执行耗时并上报;在TypeScript中启用experimentalDecorators后,可为类方法添加该装饰器,自动采集同步与异步函数的运行性能数据,并通过navigator.sendBeacon发送至服务端,结合业务上下文优化埋点,提升代码可维护性。

在JavaScript开发中,虽然JS本身不支持类似Java的注解(Annotation)语法,但通过现代前端工具链(如Babel、TypeScript装饰器等),我们可以模拟“注解”行为来实现性能埋点与监控。以下介绍如何使用函数装饰器的方式,在JS/TS项目中为函数添加性能监控能力。

什么是JS中的“注解”

JavaScript原生没有注解,但在TypeScript或使用Babel时,可以利用装饰器(Decorator)语法模拟注解行为。装饰器是一种特殊类型的声明,可用于类、方法、属性或参数上。通过装饰器,我们可以在不修改函数逻辑的前提下,自动为其添加性能监控代码。

@performanceMonitor 装饰器实现性能埋点

定义一个名为 @performanceMonitor 的方法装饰器,用于记录函数执行耗时,并上报监控系统。

function performanceMonitor(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;

descriptor.value = function (...args: any[]) { const start = performance.now(); const functionName = propertyKey;

try {
  const result = originalMethod.apply(this, args);

  // 判断是否是异步函数
  if (result && result.then && typeof result.then === 'function') {
    result.then(
      () => {
        const end = performance.now();
        console.info(`${functionName} 执行耗时: ${end - start}ms`);
        // 可在此处调用埋点上报接口
        reportPerformanceData(functionName, end - start, 'success');
      },
      (error: any) => {
        const end = performance.now();
        console.warn(`${functionName} 执行失败,耗时: ${end - start}ms`);
        reportPerformanceData(functionName, end - start, 'error', error.message);
      }
    );
  } else {
    const end = performance.now();
    console.info(`${functionName} 执行耗时: ${end - start}ms`);
    reportPerformanceData(functionName, end - start, 'success');
  }

  return result;
} catch (error) {
  const end = performance.now();
  console.warn(`${functionName} 抛出异常,耗时: ${end - start}ms`);
  reportPerformanceData(functionName, end - start, 'error', (error as Error).message);
  throw error;
}

};

return descriptor; }

// 模拟上报性能数据 function reportPerformanceData(fnName: string, duration: number, status: string, errorMsg?: string) { // 发送到监控平台,例如 Sentry、自研APM 等 navigator.sendBeacon && navigator.sendBeacon('/api/perf-log', JSON.stringify({ fnName, duration, status, errorMsg, timestamp: Date.now() })); }

在实际函数中使用性能监控注解

将 @performanceMonitor 应用于需要监控的方法,比如组件生命周期、关键业务函数等。

class UserService {

@performanceMonitor async fetchUserData(userId: string) { const res = await fetch(/api/user/${userId}); return await res.json(); }

@performanceMonitor syncCalculation(data: number[]) { let sum = 0; for (let i = 0; i < 1e8; i++) { sum += i; } return sum; } }

// 调用示例 const service = new UserService(); service.fetchUserData('123'); service.syncCalculation([1, 2, 3]);

运行后,控制台会输出类似:

fetchUserData 执行耗时: 246.78ms

syncCalculation 执行耗时: 180.12ms

同时数据会被发送到服务端用于分析。

注意事项与最佳实践

  • 确保在tsconfig.json中启用装饰器支持:"experimentalDecorators": true
  • 生产环境建议关闭console输出,仅保留上报逻辑
  • 避免在高频调用函数上使用,防止性能损耗叠加
  • 可结合用户行为链路(如页面ID、操作类型)丰富埋点上下文
  • 对于非类方法的函数,可通过高阶函数方式实现类似功能

基本上就这些。通过装饰器模拟注解,能以声明式方式统一管理性能监控,提升代码可维护性。