npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@transsionfe/web-vitals-sdk

v1.0.0

Published

Web Vitals 性能监控 SDK

Readme

@transsionfe/web-vitals-sdk

🚀 现代化的 Web Vitals 性能监控 SDK

一个专为前端应用设计的轻量级、可扩展的 Web 性能监控解决方案,支持 React、Vue 等主流框架。

✨ 特性

  • 🎯 核心指标: 全面支持 Google Web Vitals 标准 (LCP, INP, CLS, FCP, TTFB)
  • 🔧 模块化设计: 核心监控与适配器分离,易于扩展
  • 零依赖: 仅依赖官方 web-vitals
  • 🛡️ 类型安全: 完整的 TypeScript 支持
  • 📊 智能分析: 自动生成性能评分和优化建议
  • 🔌 插件化: 支持自定义上报器、存储器和适配器
  • 📱 跨平台: 支持浏览器、React Native 等环境

📦 安装

npm install @transsionfe/web-vitals-sdk
# or
yarn add @transsionfe/web-vitals-sdk
# or
pnpm add @transsionfe/web-vitals-sdk

🚀 快速开始

基础使用

import { WebVitalsMonitor } from '@transsionfe/web-vitals-sdk';

// 创建监控器实例
const monitor = new WebVitalsMonitor({
  enableConsoleLog: true,
  enableRemoteReporting: true,
  reportingEndpoint: '/api/performance/metrics',
  sampleRate: 1.0, // 100% 采样
});

// 启动监控
monitor.start();

// 监听性能指标
monitor.on('metric', (event) => {
  console.log('新的性能指标:', event.metric);
});

// 获取性能分析
const analysis = monitor.getPerformanceAnalysis();
console.log('性能评分:', analysis.score);
console.log('优化建议:', analysis.suggestions);

便捷创建

import { createWebVitalsMonitor } from '@transsionfe/web-vitals-sdk';

const monitor = createWebVitalsMonitor({
  webVitals: {
    enableConsoleLog: true,
    sampleRate: 0.5, // 50% 采样
  },
  reporter: {
    endpoint: '/api/performance/metrics',
    timeout: 10000,
  },
  adapter: {
    type: 'react',
    getUserId: () => getCurrentUserId(),
    getBuildVersion: () => process.env.REACT_APP_VERSION,
  },
});

monitor.start();

🎯 React 集成

使用 Hook

import { useWebVitals } from '@transsionfe/web-vitals-sdk';

function App() {
  const {
    metrics,
    analysis,
    isActive,
    start,
    stop,
  } = useWebVitals({
    config: {
      enableConsoleLog: process.env.NODE_ENV === 'development',
      reportingEndpoint: '/api/performance',
    },
    autoStart: true,
    onMetric: (metric) => {
      console.log('收到性能指标:', metric);
    },
  });

  return (
    <div>
      <h1>性能评分: {analysis?.score || 0}/100</h1>
      <p>状态: {isActive ? '监控中' : '已停止'}</p>
      <p>指标数量: {metrics.length}</p>

      {analysis?.suggestions.map((suggestion, index) => (
        <p key={index}>💡 {suggestion}</p>
      ))}
    </div>
  );
}

使用组件

import {
  WebVitalsMonitor,
  HttpReporter,
  LocalStorage,
  ReactAdapter,
} from '@transsionfe/web-vitals-sdk';

// 在应用初始化时创建
const monitor = new WebVitalsMonitor(
  {
    enableRemoteReporting: true,
    enableLocalStorage: true,
    bufferSize: 5,
    reportingInterval: 30000,
  },
  {
    reporter: new HttpReporter({
      endpoint: '/api/performance/metrics',
      headers: { Authorization: 'Bearer ' + getToken() },
    }),
    storage: new LocalStorage('my_app_'),
    adapter: new ReactAdapter({
      getUserId: () => store.getState().auth.user?.id,
      getBuildVersion: () => process.env.REACT_APP_VERSION,
    }),
  }
);

monitor.start();

🔧 API 文档

WebVitalsMonitor

主要的监控类,提供完整的性能监控功能。

构造函数

constructor(
  config?: WebVitalsConfig,
  dependencies?: {
    reporter?: Reporter;
    storage?: Storage;
    adapter?: Adapter;
  }
)

方法

  • start(): 启动监控
  • stop(): 停止监控
  • reportNow(): 立即上报数据
  • getCurrentMetrics(): 获取当前指标
  • getPerformanceAnalysis(): 获取性能分析
  • on(event, callback): 监听事件
  • off(event, callback): 移除监听

事件

  • metric: 收到新的性能指标
  • error: 发生错误
  • warning: 警告信息
  • info: 信息消息

配置选项

interface WebVitalsConfig {
  enableConsoleLog?: boolean; // 启用控制台日志
  enableLocalStorage?: boolean; // 启用本地存储
  enableRemoteReporting?: boolean; // 启用远程上报
  reportingEndpoint?: string; // 上报端点
  sampleRate?: number; // 采样率 (0-1)
  bufferSize?: number; // 缓冲区大小
  reportingInterval?: number; // 上报间隔(ms)
  enableLongTaskMonitoring?: boolean; // 启用长任务监控
  enableMemoryMonitoring?: boolean; // 启用内存监控
  enableResourceMonitoring?: boolean; // 启用资源监控
  thresholds?: PerformanceThresholds; // 自定义阈值
}

适配器

HttpReporter

HTTP 上报器,支持自动重试和超时控制。

const reporter = new HttpReporter({
  endpoint: '/api/performance/metrics',
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  timeout: 10000,
  retry: { attempts: 3, delay: 1000 },
});

LocalStorage

本地存储器,使用浏览器 localStorage。

const storage = new LocalStorage('web_vitals_');

ReactAdapter

React 适配器,提供 React 特定的集成支持。

const adapter = new ReactAdapter({
  getUserId: () => getCurrentUser()?.id,
  getBuildVersion: () => process.env.REACT_APP_VERSION,
  reduxStoreKey: '__REDUX_STORE__',
});

📊 性能指标

核心指标

| 指标 | 说明 | 优秀 | 需要改进 | 较差 | | -------- | -------------- | ------- | ------------- | ------- | | LCP | 最大内容绘制 | ≤ 2.5s | 2.5s - 4.0s | > 4.0s | | INP | 交互到下次绘制 | ≤ 200ms | 200ms - 500ms | > 500ms | | CLS | 累积布局偏移 | ≤ 0.1 | 0.1 - 0.25 | > 0.25 | | FCP | 首次内容绘制 | ≤ 1.8s | 1.8s - 3.0s | > 3.0s | | TTFB | 首字节时间 | ≤ 800ms | 800ms - 1.8s | > 1.8s |

扩展指标

  • 长任务监控
  • 内存使用情况
  • 资源加载性能
  • 页面加载时间
  • 设备和网络信息

🎯 高级用法

自定义上报器

import { Reporter, PerformanceReport } from '@transsionfe/web-vitals-sdk';

class CustomReporter implements Reporter {
  async report(data: PerformanceReport): Promise<void> {
    // 自定义上报逻辑
    await fetch('/custom-endpoint', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }
}

const monitor = new WebVitalsMonitor(
  {},
  {
    reporter: new CustomReporter(),
  }
);

自定义存储器

import { Storage } from '@transsionfe/web-vitals-sdk';

class CustomStorage implements Storage {
  save(key: string, data: unknown): void {
    // 自定义存储逻辑
  }

  load(key: string): unknown | null {
    // 自定义加载逻辑
    return null;
  }

  remove(key: string): void {
    // 自定义删除逻辑
  }

  clear(): void {
    // 自定义清空逻辑
  }
}

性能阈值自定义

const monitor = new WebVitalsMonitor({
  thresholds: {
    LCP: { good: 2000, needsImprovement: 3500 }, // 更严格的LCP标准
    INP: { good: 150, needsImprovement: 400 }, // 更严格的INP标准
  },
});

🔍 调试与监控

开发环境

const monitor = new WebVitalsMonitor({
  enableConsoleLog: true,
  sampleRate: 1.0,
});

// 全局访问
window.webVitalsMonitor = monitor;

// 查看性能分析
console.log(monitor.getPerformanceAnalysis());

生产环境

const monitor = new WebVitalsMonitor({
  enableConsoleLog: false,
  enableRemoteReporting: true,
  sampleRate: 0.1, // 10% 采样
  reportingEndpoint: 'https://analytics.example.com/performance',
});

🌟 最佳实践

1. 采样率设置

// 开发环境:100% 采样
const devConfig = { sampleRate: 1.0 };

// 生产环境:根据流量调整
const prodConfig = { sampleRate: 0.1 }; // 10% 用于大流量应用

2. 错误处理

monitor.on('error', (event) => {
  console.error('性能监控错误:', event.error);
  // 上报错误到错误监控系统
  errorReporter.report(event.error);
});

3. 内存管理

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
  monitor.stop();
});

4. 条件启动

// 只在特定条件下启动监控
if (shouldEnableMonitoring()) {
  monitor.start();
}

function shouldEnableMonitoring() {
  // 检查用户权限、设备性能等
  return !isLowEndDevice() && hasUserConsent();
}

📈 框架集成示例

React 集成

1. 使用 React Hook(推荐)

// src/hooks/usePerformanceMonitoring.ts
import { useWebVitals } from '@transsionfe/web-vitals-sdk';

export function usePerformanceMonitoring() {
  return useWebVitals({
    config: {
      enableConsoleLog: process.env.NODE_ENV === 'development',
      enableRemoteReporting: true,
      reportingEndpoint: '/api/performance/metrics',
      sampleRate: process.env.NODE_ENV === 'production' ? 0.1 : 1.0,
    },
    autoStart: true,
    onMetric: (metric) => {
      // 自定义指标处理
      console.log(`📊 ${metric.name}: ${metric.value}ms (${metric.rating})`);
    },
    onError: (error) => {
      console.error('性能监控错误:', error);
    },
  });
}
// src/App.tsx
import React from 'react';
import { usePerformanceMonitoring } from './hooks/usePerformanceMonitoring';

function App() {
  const { metrics, analysis, isActive } = usePerformanceMonitoring();

  return (
    <div className="App">
      <header>
        <h1>我的应用</h1>
        {process.env.NODE_ENV === 'development' && (
          <div className="performance-info">
            <p>性能监控: {isActive ? '✅ 活跃' : '❌ 停止'}</p>
            <p>性能评分: {analysis?.score || 0}/100</p>
            <p>指标数量: {metrics.length}</p>
          </div>
        )}
      </header>
      {/* 应用内容 */}
    </div>
  );
}

export default App;

2. 使用 Context 提供者模式

// src/contexts/PerformanceContext.tsx
import React, { createContext, useContext, ReactNode } from 'react';
import { useWebVitals, UseWebVitalsReturn } from '@transsionfe/web-vitals-sdk';

const PerformanceContext = createContext<UseWebVitalsReturn | null>(null);

interface PerformanceProviderProps {
  children: ReactNode;
}

export function PerformanceProvider({ children }: PerformanceProviderProps) {
  const vitals = useWebVitals({
    config: {
      enableConsoleLog: process.env.NODE_ENV === 'development',
      enableRemoteReporting: true,
      reportingEndpoint: '/api/performance/metrics',
      enableLocalStorage: true,
      bufferSize: 5,
    },
    autoStart: true,
  });

  return (
    <PerformanceContext.Provider value={vitals}>
      {children}
    </PerformanceContext.Provider>
  );
}

export function usePerformance() {
  const context = useContext(PerformanceContext);
  if (!context) {
    throw new Error('usePerformance must be used within PerformanceProvider');
  }
  return context;
}
// src/main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { PerformanceProvider } from './contexts/PerformanceContext';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <PerformanceProvider>
      <App />
    </PerformanceProvider>
  </React.StrictMode>
);

3. Next.js 应用级集成

// pages/_app.tsx
import { useEffect } from 'react';
import type { AppProps } from 'next/app';
import { createWebVitalsMonitor } from '@transsionfe/web-vitals-sdk';

export default function MyApp({ Component, pageProps }: AppProps) {
  useEffect(() => {
    const monitor = createWebVitalsMonitor({
      webVitals: {
        enableRemoteReporting: process.env.NODE_ENV === 'production',
        enableConsoleLog: process.env.NODE_ENV === 'development',
        reportingEndpoint: '/api/performance',
        sampleRate: 0.1, // 10% 采样
      },
      adapter: {
        type: 'react',
        getUserId: () => {
          // 从你的认证系统获取用户ID
          return window.localStorage.getItem('userId') || undefined;
        },
        getBuildVersion: () => process.env.NEXT_PUBLIC_APP_VERSION || 'unknown',
      },
    });

    monitor.start();

    // 页面卸载时清理
    return () => monitor.stop();
  }, []);

  return <Component {...pageProps} />;
}
// pages/api/performance.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const performanceData = req.body;

    // 处理性能数据
    console.log('收到性能数据:', {
      url: performanceData.url,
      metrics: performanceData.metrics.length,
      score: calculateScore(performanceData.metrics),
    });

    // 这里可以存储到数据库或发送到分析服务

    res.status(200).json({ success: true });
  } else {
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

function calculateScore(metrics: any[]) {
  // 简单的评分计算
  const goodMetrics = metrics.filter((m) => m.rating === 'good').length;
  return Math.round((goodMetrics / metrics.length) * 100);
}

Vue 集成

1. Vue 3 Composition API

// src/composables/usePerformanceMonitoring.ts
import { ref, onMounted, onUnmounted } from 'vue';
import {
  WebVitalsMonitor,
  PerformanceMetric,
  PerformanceAnalysis,
} from '@transsionfe/web-vitals-sdk';

export function usePerformanceMonitoring() {
  const monitor = ref<WebVitalsMonitor | null>(null);
  const metrics = ref<PerformanceMetric[]>([]);
  const analysis = ref<PerformanceAnalysis | null>(null);
  const isActive = ref(false);

  onMounted(() => {
    monitor.value = new WebVitalsMonitor({
      enableConsoleLog: import.meta.env.DEV,
      enableRemoteReporting: true,
      reportingEndpoint: '/api/performance/metrics',
      sampleRate: import.meta.env.PROD ? 0.1 : 1.0,
    });

    // 监听事件
    monitor.value.on('metric', (event) => {
      if (event.metric) {
        metrics.value.push(event.metric);
        analysis.value = monitor.value!.getPerformanceAnalysis();
      }
    });

    monitor.value.on('info', (event) => {
      if (event.message?.includes('启动')) {
        isActive.value = true;
      } else if (event.message?.includes('停止')) {
        isActive.value = false;
      }
    });

    monitor.value.start();
  });

  onUnmounted(() => {
    monitor.value?.stop();
  });

  const reportNow = () => {
    monitor.value?.reportNow();
  };

  return {
    metrics: readonly(metrics),
    analysis: readonly(analysis),
    isActive: readonly(isActive),
    reportNow,
  };
}
<!-- src/App.vue -->
<template>
  <div id="app">
    <header>
      <h1>我的 Vue 应用</h1>
      <div v-if="isDev" class="performance-info">
        <p>性能监控: {{ isActive ? '✅ 活跃' : '❌ 停止' }}</p>
        <p>性能评分: {{ analysis?.score || 0 }}/100</p>
        <p>指标数量: {{ metrics.length }}</p>
        <button @click="reportNow">立即上报</button>
      </div>
    </header>
    <main>
      <!-- 应用内容 -->
    </main>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue';
import { usePerformanceMonitoring } from './composables/usePerformanceMonitoring';

const { metrics, analysis, isActive, reportNow } = usePerformanceMonitoring();

const isDev = computed(() => import.meta.env.DEV);
</script>

2. Vue 3 全局插件

// src/plugins/webVitals.ts
import { App } from 'vue';
import { createWebVitalsMonitor, WebVitalsMonitor } from '@transsionfe/web-vitals-sdk';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $webVitals: WebVitalsMonitor;
  }
}

export default {
  install(app: App) {
    const monitor = createWebVitalsMonitor({
      webVitals: {
        enableConsoleLog: import.meta.env.DEV,
        enableRemoteReporting: true,
        reportingEndpoint: '/api/performance/metrics',
        sampleRate: import.meta.env.PROD ? 0.1 : 1.0,
      },
    });

    // 全局属性
    app.config.globalProperties.$webVitals = monitor;

    // 全局提供
    app.provide('webVitals', monitor);

    // 启动监控
    monitor.start();

    // 应用卸载时清理
    const originalUnmount = app.unmount;
    app.unmount = function () {
      monitor.stop();
      originalUnmount.call(this);
    };
  },
};
// src/main.ts
import { createApp } from 'vue';
import webVitalsPlugin from './plugins/webVitals';
import App from './App.vue';

const app = createApp(App);

app.use(webVitalsPlugin);

app.mount('#app');

3. Nuxt.js 集成

// plugins/web-vitals.client.ts
import { createWebVitalsMonitor } from '@transsionfe/web-vitals-sdk';

export default defineNuxtPlugin(() => {
  const { $config } = useNuxtApp();

  const monitor = createWebVitalsMonitor({
    webVitals: {
      enableRemoteReporting: process.env.NODE_ENV === 'production',
      enableConsoleLog: process.env.NODE_ENV === 'development',
      reportingEndpoint: '/api/performance',
      sampleRate: 0.1,
    },
  });

  monitor.start();

  // 页面切换时上报数据
  const router = useRouter();
  router.afterEach(() => {
    monitor.reportNow();
  });

  return {
    provide: {
      webVitals: monitor,
    },
  };
});
// server/api/performance.post.ts
export default defineEventHandler(async (event) => {
  const body = await readBody(event);

  // 处理性能数据
  console.log('收到性能数据:', {
    url: body.url,
    userAgent: body.userAgent,
    metrics: body.metrics.length,
    timestamp: new Date(body.timestamp).toISOString(),
  });

  // 存储到数据库或发送到分析服务

  return { success: true };
});

通用原生 JavaScript 集成

// 适用于任何框架或纯 JS 项目
import { createWebVitalsMonitor } from '@transsionfe/web-vitals-sdk';

// 创建全局监控实例
window.performanceMonitor = createWebVitalsMonitor({
  webVitals: {
    enableConsoleLog: process.env.NODE_ENV === 'development',
    enableRemoteReporting: true,
    reportingEndpoint: '/api/performance/metrics',
    sampleRate: 0.1,
  },
});

// 启动监控
window.performanceMonitor.start();

// 页面卸载时清理
window.addEventListener('beforeunload', () => {
  window.performanceMonitor?.stop();
});

🤝 贡献

欢迎提交 Issues 和 Pull Requests!

📄 许可证

MIT License

🔗 相关链接


Transsion Frontend Team 开发维护 ❤️