front-end-monitor
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

front-end-monitor

npm version npm downloads MIT License bundle size

轻量级前端监控工具,用于捕获和上报应用性能、错误和用户行为数据,帮助开发者精准定位问题并优化用户体验。零依赖设计,gzip后体积小于5KB,支持主流浏览器及Vue/React框架集成。

核心特性

  • 极致轻量:零依赖,gzip后<5KB,不影响页面性能
  • 📊 全面性能监控:自动采集FP、FCP、LCP、CLS等核心性能指标
  • 🚨 多维错误追踪:捕获JS运行时错误、Promise拒绝、资源加载错误及框架组件错误
  • 🖱️ 用户行为分析:追踪点击、滚动、输入等交互行为,支持元素路径解析
  • 🔒 隐私保护机制:敏感输入自动掩码、数据采样率控制、无Cookie追踪
  • ⚙️ 高度可配置:灵活开关各模块功能,自定义上报策略和数据处理规则
  • 📤 可靠上报系统:基于Beacon API的批量上报机制,支持失败重试

快速安装

# 通过npm安装
npm install front-end-monitor --save

# 或通过yarn安装
yarn add front-end-monitor

快速开始

基础集成

import { initMonitor } from 'front-end-monitor';

// 在应用入口处初始化监控
initMonitor({
  reportUrl: 'https://your-monitor-api.com/report', // 数据上报接口
  appId: 'your-app-id',                            // 应用唯一标识
  samplingRate: 0.5,                               // 50%采样率
  enablePerformance: true,                         // 启用性能监控
  enableError: true,                               // 启用错误监控
  enableBehavior: true                             // 启用行为监控
});

高级配置示例

initMonitor({
  reportUrl: 'https://monitor-api.com/v1/report',
  appId: 'production-app',
  samplingRate: 0.3,         // 30%采样率降低生产环境数据量
  reportBatchSize: 10,       // 批量上报条数
  reportInterval: 8000,      // 8秒上报间隔
  
  // 性能监控配置
  performance: {
    captureMetrics: ['LCP', 'CLS', 'FID'], // 只采集核心性能指标
    logTiming: false                      // 关闭详细时序日志
  },
  
  // 错误监控配置
  error: {
    captureUnhandledRejections: true,      // 捕获未处理的Promise拒绝
    maxErrorStackLength: 150              // 限制错误堆栈长度
  },
  
  // 行为监控配置
  behavior: {
    captureClicks: true,                   // 启用点击监控
    captureScrolls: false,                 // 关闭滚动监控
    inputMasking: true,                    // 启用输入掩码
    inputMaxLength: 80                     // 输入内容最大长度
  }
});

完整配置选项

选项 类型 默认值 描述
reportUrl string undefined 必需 数据上报API地址
appId string undefined 必需 应用唯一标识符
enablePerformance boolean true 是否启用性能监控
enableError boolean true 是否启用错误监控
enableBehavior boolean true 是否启用行为监控
samplingRate number 1.0 采样率 (0.0-1.0),1.0表示全量采集
reportBatchSize number 5 批量上报数据条数
reportInterval number 10000 上报间隔(毫秒)
inputMasking boolean true 是否对敏感输入进行掩码处理
inputMaxLength number 200 输入内容最大记录长度
debug boolean false 调试模式,开启控制台日志

监控能力详解

性能指标监控

指标 描述 重要性
FP (First Paint) 首次绘制时间 ⭐⭐
FCP (First Contentful Paint) 首次内容绘制时间 ⭐⭐⭐⭐
LCP (Largest Contentful Paint) 最大内容渲染时间 ⭐⭐⭐⭐⭐
CLS (Cumulative Layout Shift) 累积布局偏移 ⭐⭐⭐⭐
FID (First Input Delay) 首次输入延迟 ⭐⭐⭐⭐
TTI (Time to Interactive) 可交互时间 ⭐⭐⭐

错误监控范围

  • JavaScript运行时错误(SyntaxError/ReferenceError等)
  • 未处理的Promise拒绝(UnhandledPromiseRejection)
  • 资源加载错误(图片/脚本/CSS加载失败)
  • 跨域脚本错误(通过CORS配置捕获)
  • Vue/React组件渲染错误(需框架集成)

用户行为追踪

  1. 点击事件

    • 元素路径(如body>div.container>button.submit
    • 点击位置(clientX/clientY)
    • 元素属性(ID/类名/标签名)
  2. 滚动行为

    • 滚动深度(scrollTop/scrollLeft)
    • 滚动方向(向上/向下)
    • 视口停留区域
  3. 输入监控

    • 输入类型(文本/密码/邮箱等)
    • 输入内容(敏感字段自动掩码)
    • 输入持续时间

隐私保护机制

  1. 敏感字段自动掩码:检测到密码/信用卡等字段时自动显示为••••••
  2. 输入长度限制:默认只记录前200个字符,可自定义inputMaxLength
  3. 智能采样策略:通过samplingRate控制数据采集范围
  4. 无用户身份追踪:不采集Cookie/ localStorage等用户标识信息
  5. 数据脱敏处理:自动过滤password/token等敏感DOM属性

数据上报机制

graph TD
    A[事件触发] --> B{采样率检查}
    B -->|通过| C[数据标准化]
    B -->|未通过| D[丢弃]
    C --> E[数据缓存]
    E --> F{达到批量大小或超时?}
    F -->|| G[Beacon API上报]
    F -->|| E
    G --> H[上报成功]
    G -->|失败| I[降级到Fetch/XHR]
  • Beacon API优先:页面卸载时仍能可靠上报数据
  • 批量+定时上报:减少网络请求次数,降低服务器压力
  • 失败重试机制:采用指数退避算法处理网络错误
  • 数据压缩传输:自动序列化并压缩上报数据
  • 内存保护策略:限制队列长度防止内存溢出

框架集成示例

Vue框架集成

import { createApp } from 'vue';
import { initMonitor } from 'front-end-monitor';
import App from './App.vue';

const monitor = initMonitor({
  reportUrl: 'https://monitor-api.com/report',
  appId: 'vue-app',
  enableError: true
});

const app = createApp(App);

// 注册Vue错误处理器
app.config.errorHandler = (error, vm, info) => {
  monitor.handleVueError(error, vm, info);
};

app.mount('#app');

React框架集成

import { initMonitor } from 'front-end-monitor';
import React, { Component } from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const monitor = initMonitor({
  reportUrl: 'https://monitor-api.com/report',
  appId: 'react-app'
});

// 错误边界组件
class ErrorBoundary extends Component {
  state = { error: null, errorInfo: null };

  componentDidCatch(error, errorInfo) {
    // 上报React组件错误
    monitor.handleReactError(error, errorInfo);
    this.setState({ error, errorInfo });
  }

  render() {
    if (this.state.error) {
      return <div>组件渲染错误,请稍后重试</div>;
    }
    return this.props.children;
  }
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ErrorBoundary>
      <App />
    </ErrorBoundary>
  </React.StrictMode>
);

自定义埋点上报

// 在需要埋点的位置调用
window.frontendMonitor?.report({
  type: 'custom',
  eventName: 'product_view',
  data: {
    productId: 'P12345',
    category: 'electronics',
    viewTime: 12.5, // 浏览时长(秒)
    // 自动附加性能上下文
    performance: window.frontendMonitor.getPerformanceSnapshot()
  }
});

开发与贡献

欢迎提交PR改进项目!开发流程如下:

  1. Fork项目仓库
  2. 创建特性分支:git checkout -b feature/new-feature
  3. 提交更改:git commit -m 'Add new feature: xxx'
  4. 推送分支:git push origin feature/new-feature
  5. 创建Pull Request

本地开发命令:

# 安装依赖
npm install

# 运行测试
npm test

# 代码规范检查
npm run lint

# 构建产物
npm run build

许可证

MIT License © 2023 front-end-monitor

Package Sidebar

Install

npm i front-end-monitor

Weekly Downloads

0

Version

1.0.0

License

MIT

Unpacked Size

38.5 kB

Total Files

18

Last publish

Collaborators

  • axin666