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

在JavaScript开发中,虽然JS本身不支持类似Java的注解(Annotation)语法,但通过现代前端工具链(如Babel、TypeScript装饰器等),我们可以模拟“注解”行为来实现性能埋点与监控。以下介绍如何使用函数装饰器的方式,在JS/TS项目中为函数添加性能监控能力。
JavaScript原生没有注解,但在TypeScript或使用Babel时,可以利用装饰器(Decorator)语法模拟注解行为。装饰器是一种特殊类型的声明,可用于类、方法、属性或参数上。通过装饰器,我们可以在不修改函数逻辑的前提下,自动为其添加性能监控代码。
定义一个名为 @performanceMonitor 的方法装饰器,用于记录函数执行耗时,并上报监控系统。
function performanceMonitor(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
<p>descriptor.value = function (...args: any[]) {
const start = performance.now();
const functionName = propertyKey;</p><pre class='brush:php;toolbar:false;'>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 {
<p>@performanceMonitor
async fetchUserData(userId: string) {
const res = await fetch(<code>/api/user/${userId}</code>);
return await res.json();
}</p><p>@performanceMonitor
syncCalculation(data: number[]) {
let sum = 0;
for (let i = 0; i < 1e8; i++) {
sum += i;
}
return sum;
}
}</p><p>// 调用示例
const service = new UserService();
service.fetchUserData('123');
service.syncCalculation([1, 2, 3]);</p>运行后,控制台会输出类似:
fetchUserData 执行耗时: 246.78ms
syncCalculation 执行耗时: 180.12ms
同时数据会被发送到服务端用于分析。
"experimentalDecorators": true
基本上就这些。通过装饰器模拟注解,能以声明式方式统一管理性能监控,提升代码可维护性。
以上就是JS注解怎么标注性能监控_ 性能埋点与监控函数的JS注解使用说明的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号