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

lr-monitor-sdk

v1.0.0

Published

轻量级前端监控SDK,支持Vue3、React、原生JS等多种框架,提供用户行为追踪、错误监控、性能分析功能

Downloads

6

Readme

lr-monitor-sdk

npm version TypeScript License: MIT

轻量级前端监控SDK,支持Vue3、React、原生JS等多种框架,提供用户行为追踪、错误监控、性能分析功能。

✨ 特性

  • 🚀 轻量级设计 - 压缩后仅 ~15KB,对页面性能影响极小
  • 🎯 多框架支持 - Vue3、React、原生JS 等主流框架
  • 📊 Web Vitals - 自动收集 FCP、LCP、FID、CLS 等性能指标
  • 🔍 错误监控 - JS错误、Promise异常、资源加载失败
  • 👆 用户行为 - 点击、导航、页面停留时间等
  • 🛡️ 数据保护 - sendBeacon API 确保页面卸载时数据不丢失
  • 非阻塞上报 - 异步批量上报,不影响页面性能
  • 🎛️ 灵活配置 - 支持自定义上报端点、采样率、过滤规则

📦 安装

NPM 安装

npm install lr-monitor-sdk

pnpm 安装

pnpm add lr-monitor-sdk

Yarn 安装

yarn add lr-monitor-sdk

CDN 引入

<!-- 生产环境 -->
<script src="https://unpkg.com/lr-monitor-sdk@latest/dist/index.js"></script>

<!-- 开发环境(包含调试信息) -->
<script src="https://unpkg.com/lr-monitor-sdk@latest/dist/index.dev.js"></script>

🚀 快速开始

Vue 3 项目

// main.ts
import { createApp } from 'vue'
import { createMonitor } from 'lr-monitor-sdk'
import App from './App.vue'

const app = createApp(App)

// 创建监控实例
const monitor = createMonitor({
  apiUrl: 'http://your-api-domain.com/api/monitor/report',
  apiPassword: 'your-api-password',
  enableBatch: true,
  batchSize: 5,
  batchInterval: 10000,
  debug: false
})

// 安装Vue插件
app.use(monitor)

app.mount('#app')

React 项目

// App.tsx
import React, { useEffect } from 'react'
import { createMonitor } from 'lr-monitor-sdk'

const monitor = createMonitor({
  apiUrl: 'http://your-api-domain.com/api/monitor/report',
  apiPassword: 'your-api-password',
  enableBatch: true,
  batchSize: 5,
  batchInterval: 10000
})

function App() {
  useEffect(() => {
    // 初始化监控
    monitor.init()

    // 页面加载完成事件
    monitor.track('page_loaded', '页面加载完成', {
      component: 'App',
      loadTime: performance.now()
    })
  }, [])

  return (
    <div className="App">
      <button 
        onClick={() => {
          monitor.track('user_action', '用户点击按钮', {
            buttonName: 'demo-button'
          })
        }}
      >
        点击测试
      </button>
    </div>
  )
}

export default App

原生 JavaScript

<!DOCTYPE html>
<html>
<head>
    <title>监控SDK示例</title>
    <script src="https://unpkg.com/@lr-monitor/sdk@latest/dist/index.js"></script>
</head>
<body>
    <button id="testBtn">点击测试</button>

    <script>
        // 创建监控实例
        const monitor = LRMonitor.createMonitor({
            apiUrl: 'http://your-api-domain.com/api/monitor/report',
            apiPassword: 'your-api-password',
            enableBatch: true,
            debug: true
        })

        // 初始化
        monitor.init()

        // 监听用户交互
        document.getElementById('testBtn').addEventListener('click', () => {
            monitor.track('user_action', '用户点击按钮', {
                buttonId: 'testBtn',
                timestamp: Date.now()
            })
        })
    </script>
</body>
</html>

⚙️ 配置选项

interface MonitorConfig {
  // 上报接口地址(必填)
  apiUrl: string
  
  // API密码,用于后端验证(必填)
  apiPassword: string
  
  // 批量上报配置
  enableBatch?: boolean        // 是否启用批量上报 (默认: true)
  batchSize?: number          // 批量上报的最大条数 (默认: 10)
  batchInterval?: number      // 批量上报的时间间隔ms (默认: 5000)
  
  // 重试配置
  retryTimes?: number         // 上报失败重试次数 (默认: 3)
  
  // 调试选项
  debug?: boolean            // 是否在控制台输出调试信息 (默认: false)
}

📋 API 文档

创建监控实例

import { createMonitor } from 'lr-monitor-sdk'

const monitor = createMonitor(config: MonitorConfig)

初始化监控

// Vue项目中,使用app.use()会自动调用init()
// React/原生JS项目需手动调用
monitor.init()

手动上报事件

monitor.track(
  code: string,           // 监控代码
  msg: string,           // 消息描述  
  extraInfo?: object,    // 额外信息
  error?: Error | string // 错误对象
)

// 示例
monitor.track('user_login', '用户登录成功', {
  userId: '12345',
  loginMethod: 'email'
})

设置用户信息

monitor.setUser(userId: string, userInfo?: object)

// 示例
monitor.setUser('user123', {
  name: '张三',
  role: 'admin',
  department: '技术部'
})

强制上报

monitor.flush() // 立即发送队列中的所有数据

销毁实例

monitor.destroy() // 清理监听器和定时器

📊 自动收集的数据

性能指标

  • 页面加载时间 - window.onload 时间
  • DOM准备时间 - DOMContentLoaded 时间
  • 首次绘制 - First Paint (FP)
  • 首次内容绘制 - First Contentful Paint (FCP)
  • 最大内容绘制 - Largest Contentful Paint (LCP)
  • 首次输入延迟 - First Input Delay (FID)
  • 累积布局偏移 - Cumulative Layout Shift (CLS)

错误监控

  • JavaScript 错误 - window.onerror
  • Promise 未处理拒绝 - unhandledrejection
  • 资源加载失败 - 图片、脚本、样式等
  • Vue 组件错误 (Vue项目)

用户行为

  • 页面浏览 - 路由变化、页面停留时间
  • 点击事件 - 按钮、链接点击
  • 表单交互 - 输入、提交
  • 滚动行为 - 页面滚动深度

环境信息

  • 浏览器信息 - UserAgent、版本
  • 设备信息 - 屏幕分辨率、视窗大小
  • 网络状态 - 在线/离线状态
  • 页面信息 - URL、标题、来源页面

🔧 高级用法

自定义错误处理

monitor.onError((error, context) => {
  // 自定义错误处理逻辑
  console.log('监控到错误:', error)
  
  // 可以选择是否继续上报
  return true // false 则不上报此错误
})

数据预处理

monitor.beforeSend((data) => {
  // 数据上报前的预处理
  data.customField = 'custom_value'
  return data
})

条件采样

const monitor = createMonitor({
  endpoint: 'http://your-api.com/report',
  sampleRate: 0.1, // 仅采样10%的用户
  
  // 或使用自定义采样逻辑
  shouldSample: () => {
    return Math.random() < 0.5 // 50%采样率
  }
})

🚨 常见问题

Q: 如何减少数据上报量?

A: 可以通过以下方式优化:

  • 调整 sampleRate 采样率
  • 增加 batchSize 批量大小
  • 调整 flushInterval 上报间隔
  • 使用自定义过滤规则

Q: 支持哪些浏览器?

A: 支持所有现代浏览器:

  • Chrome >= 60
  • Firefox >= 55
  • Safari >= 12
  • Edge >= 79

Q: 如何在开发环境中调试?

A: 启用调试模式:

const monitor = createMonitor({
  endpoint: 'http://localhost:3000/api/monitor/report',
  enableDebug: true // 控制台输出详细日志
})

Q: 数据上报失败怎么办?

A: SDK内置了重试机制:

  • 自动重试 3 次
  • 使用指数退避策略
  • 失败数据会缓存到 localStorage

📄 License

MIT

Copyright (c) 2025 LR Monitor Team

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📞 支持

  • 📧 Email: [email protected]
  • 🐛 Issues: https://github.com/lr-monitor/sdk/issues
  • 📖 Documentation: https://lr-monitor.com/docs