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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@wlydfe/track-js

v0.0.8

Published

埋点sdk

Readme

@wlydfe/track-js

一个前端埋点跟踪 SDK,支持多种跟踪器类型,提供统一的埋点接口。

特性

  • 🚀 多跟踪器支持: 支持 Hina、HinaUni 等多种跟踪器
  • 📊 自动埋点: 支持页面浏览、元素曝光等自动埋点
  • 🎯 元素曝光: 支持基于 Intersection Observer 的元素曝光监听
  • 🔧 灵活配置: 支持开发/生产环境配置
  • 📱 跨平台: 支持 Web 和小程序环境
  • 🛡️ 类型安全: 完整的 TypeScript 类型定义
  • 🎨 单例模式: 全局统一的跟踪器实例管理
  • 🔄 自动环境检测: 自动检测运行环境并挂载到相应全局对象

安装

npm install @wlydfe/track-js

快速开始

基础用法

import Track from '@wlydfe/track-js';

// 创建跟踪器实例(会自动挂载到全局对象)
const track = new Track();

// 初始化跟踪器
track.init({
  isProd: true, // 或 false
  trackerType: 'hina', // 跟踪器类型
  debug: false, // 是否开启调试模式
  autoTrack: true, // 是否开启自动埋点
  config: {
    project: 'your-project-name',
    token: 'your-token'
  }
});

使用预创建实例

import { wlydTrack } from '@wlydfe/track-js';

// 直接使用预创建的实例(已自动挂载到全局对象)
wlydTrack.init({
  isProd: true,
  trackerType: 'hina',
  config: {
    project: 'your-project-name',
    token: 'your-token'
  }
});

全局对象访问

SDK 会自动检测运行环境并挂载到相应的全局对象:

Web 环境:

// 在浏览器中可以直接使用
window.$wlydTrack.track('button_click', { id: 'submit' });

uni-app 环境:

// 在小程序中可以直接使用
uni.$wlydTrack.track('button_click', { id: 'submit' });

单例模式使用

import Track from '@wlydfe/track-js';

// 获取单例实例
const track = Track.getInstance();

track.init({
  isProd: true,
  trackerType: 'hina',
  config: {
    project: 'your-project-name',
    token: 'your-token'
  }
});

高级用法

环境自动检测

SDK 会自动检测运行环境并选择合适的跟踪器:

import { wlydTrack } from '@wlydfe/track-js';

// 不指定 trackerType,SDK 会自动选择
wlydTrack.init({
  isProd: true,
  // trackerType 会自动根据环境选择 'hina' 或 'hina_uni'
  config: {
    project: 'your-project',
    token: 'your-token'
  }
});

公共属性管理

// 注册公共属性
wlydTrack.registerCommonProperties({
  enterprise_id: 'enterprise_123',
  app_version: '1.0.0',
  app_id: 'app_core',
});

// 获取公共属性
const commonProps = wlydTrack.getCommonProperties();

// 清除公共属性
wlydTrack.clearCommonProperties();

元素曝光高级配置

// 配置复杂的曝光监听
const banner = document.getElementById('banner');
wlydTrack.addElementExposure(banner, {
  threshold: 0.8,        // 80% 可见才触发
  duration: 2000,        // 持续 2 秒
  once: false,           // 可以多次触发
  rootMargin: '50px'     // 提前 50px 开始计算
}, {
  banner_type: 'hero',
  campaign_id: 'summer_2024'
});

小程序环境使用

// 在 uni-app 中使用
import { wlydTrack } from '@wlydfe/track-js';

// 初始化小程序跟踪器
wlydTrack.init({
  isProd: true,
  trackerType: 'hina_uni',
  config: {
    project: 'your-miniprogram',
    token: 'your-token',
    app: getApp() // 传入小程序实例
  }
});

// 在小程序页面中使用
Page({
  onLoad() {
    // 页面加载事件
    uni.wlydTrack.track('page_load', {
      page_name: 'product_detail',
      product_id: '12345'
    });
  }
});

API 文档

初始化

init(options, callback?)

初始化跟踪器

参数:

  • options.isProd: 环境配置 (true | false)
  • options.trackerType: 跟踪器类型 ('hina' | 'hina_uni')
  • options.debug: 是否开启调试模式 (默认: false)
  • options.autoTrack: 是否开启自动埋点 (默认: true)
  • options.config: 跟踪器特定配置
  • callback: 初始化完成回调

示例:

track.init({
  isProd: true,
  trackerType: 'hina',
  debug: true,
  autoTrack: true,
  config: {
    project: 'WlydRelease',
    token: 'xcmx1b2a'
  }
}, () => {
  console.log('跟踪器初始化完成');
});

事件跟踪

track(eventType, data?)

发送跟踪事件

参数:

  • eventType: 事件类型 (字符串)
  • data: 事件数据 (可选)

示例:

// 自定义事件
track.track('button_click', {
  button_id: 'submit_btn',
  page_name: 'checkout'
});

// 页面浏览事件
track.track('page_view', {
  page_url: '/products',
  page_title: '产品列表'
});

用户管理

setUser(userId, userInfo?)

设置用户信息

参数:

  • userId: 用户ID
  • userInfo: 用户信息对象 (可选)

示例:

track.setUser('user123', {
  name: '张三',
  email: '[email protected]',
  vip_level: 'gold'
});

公共属性管理

registerCommonProperties(properties)

注册公共属性

参数:

  • properties: 公共属性对象

示例:

track.registerCommonProperties({
  app_id: 8,
  platform: 'web',
  version: '1.0.0',
  enterprise_id: 'enterprise_123'
});

getCommonProperties()

获取当前公共属性

返回值: 公共属性对象

clearCommonProperties()

清除所有公共属性

元素曝光

addElementExposure(element, options?, data?)

添加元素曝光监听

参数:

  • element: DOM 元素
  • options: 曝光配置 (可选)
    • threshold: 曝光阈值,元素可见面积占元素总面积的百分比 (默认: 0.5)
    • duration: 曝光持续时间,单位毫秒 (默认: 1000ms)
    • once: 是否只触发一次 (默认: true)
    • root: 根元素,用于计算可见性 (默认: viewport)
    • rootMargin: 根元素的边距,用于扩展或缩小根边界框 (默认: '0px')
  • data: 自定义数据 (可选)

示例:

const element = document.getElementById('banner');
track.addElementExposure(element, {
  threshold: 0.5, // 曝光阈值
  duration: 1000, // 曝光持续时间
  once: true,     // 只触发一次
  rootMargin: '0px'
}, {
  banner_id: 'main_banner',
  position: 'top'
});

removeElementExposure(exposureElement)

移除指定元素曝光监听

参数:

  • exposureElement: 曝光元素对象

removeAllElementExposure()

移除所有元素曝光监听

uni-app中添加元素曝光监听

示例:

<template>
	<view class="container">
		<text>{{appear ? '小球出现' : '小球消失'}}</text>
		<view class="page-section">
			<scroll-view class="scroll-view" scroll-y>
				<view class="scroll-area">
					<text class="notice">向下滚动让小球出现</text>
					<view class="ball"></view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>
<script>
	let observer = null;
	export default {
		data() {
			return {
				appear: false
			}
		},
		onReady() {
			observer = uni.createIntersectionObserver(this);
            observer.relativeTo('.scroll-view').observe('.ball', (res) => {
              if (res.intersectionRatio > 0 && !this.appear) {
                this.appear = true;
                uni.$wlydTrack.track('customer', {
                  name: '张三',
                  age: 18
                });
              } else if (!res.intersectionRatio > 0 && this.appear) {
                this.appear = false;
              }
            })
		},
		onUnload() {
			if (observer) {
				observer.disconnect()
			}
		}
	}
</script>
<style>
	view,page {
		display: flex;
		flex-direction: column;
	}

	.scroll-view {
		height: 400rpx;
		background: #fff;
		border: 1px solid #ccc;
		box-sizing: border-box;
	}

	.scroll-area {
		height: 1300rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		transition: .5s;
	}

	.notice {
		margin-top: 150rpx;
		margin: 150rpx 0 400rpx 0;
	}

	.ball {
		width: 200rpx;
		height: 200rpx;
		background: #1AAD19;
		border-radius: 50%;
	}
</style>

removeElementExposure(exposureElement)

工具方法

getInstance()

获取单例实例 (静态方法)

isInit

检查是否已初始化 (只读属性)

isUniEnv

获取运行环境类型 (只读属性)

  • true: uni-app 环境
  • false: web 环境

destroy()

销毁跟踪器实例

配置说明

环境配置

  • 开发环境 (isProd: false): 使用测试配置,开启详细日志
  • 生产环境 (isProd: true): 使用正式配置,优化性能

跟踪器类型

Hina 跟踪器

适用于 Web 环境,支持完整的埋点功能。

配置参数:

{
  project: string, // 项目名称
  token: string,    // 访问令牌
  serverUrl?: string // 数据收集地址
}

HinaUni 跟踪器

适用于小程序环境。

配置参数:

{
  project: string, // 项目名称
  token: string,   // 访问令牌
  serverUrl?: string // 数据收集地址(可选)
  app: Object      // 小程序实例
}

事件类型

SDK 内置了以下事件类型:

  • element_exposure: 元素曝光
  • page_exposure: 页面曝光
  • viewport_exposure: 视口曝光

你也可以使用自定义事件类型。

TrackEventType 命名规范

1. 命名格式

  • 全小写字母
  • 使用下划线分隔单词
  • 采用动词_名词的格式
  • 保持简洁明了

2. 命名结构

[动作]_[对象]_[场景]

分类规范

1. 用户行为事件

点击事件

// 基础格式: click_[对象]
'click_button'           // 按钮点击
'click_link'             // 链接点击
'click_image'            // 图片点击
'click_card'             // 卡片点击
'click_tab'              // 标签页点击
'click_menu'             // 菜单点击
'click_icon'             // 图标点击

// 带场景的格式: click_[对象]_[场景]
'click_button_submit'    // 提交按钮点击
'click_button_cancel'    // 取消按钮点击
'click_link_external'    // 外部链接点击
'click_tab_navigation'   // 导航标签点击

输入事件

// 基础格式: input_[动作]
'input_focus'            // 输入框获得焦点
'input_blur'             // 输入框失去焦点
'input_change'           // 输入内容变化
'input_submit'           // 表单提交

// 带场景的格式: input_[动作]_[场景]
'input_search'           // 搜索输入
'input_login'            // 登录输入
'input_register'         // 注册输入
'input_comment'          // 评论输入

滚动事件

'scroll_page'            // 页面滚动
'scroll_list'            // 列表滚动
'scroll_gallery'         // 画廊滚动
'scroll_timeline'        // 时间线滚动

拖拽事件

'drag_start'             // 开始拖拽
'drag_move'              // 拖拽移动
'drag_end'               // 结束拖拽
'drag_drop'              // 拖拽放置

2. 业务功能事件

用户认证

'user_login'             // 用户登录
'user_logout'            // 用户登出
'user_register'          // 用户注册
'user_profile_update'    // 用户资料更新
'user_password_change'   // 密码修改

内容交互

'content_view'           // 内容查看
'content_share'          // 内容分享
'content_like'           // 内容点赞
'content_comment'        // 内容评论
'content_favorite'       // 内容收藏
'content_download'       // 内容下载
'content_upload'         // 内容上传

购物相关

'cart_add'               // 加入购物车
'cart_remove'            // 从购物车移除
'cart_update'            // 购物车更新
'checkout_start'         // 开始结账
'checkout_complete'      // 结账完成
'payment_success'        // 支付成功
'payment_failed'         // 支付失败

3. 系统事件

错误事件

'error_network'          // 网络错误
'error_js'               // JavaScript错误
'error_api'              // API错误
'error_validation'       // 验证错误
'error_timeout'          // 超时错误

5. 曝光事件(已定义)

'element_exposure'       // 元素曝光
'page_exposure'          // 页面曝光
'viewport_exposure'      // 视口曝光

开发

构建

# 开发模式
npm run dev

# 生产构建
npm run build

# 类型定义构建
npm run build:types

项目结构

src/
├── config/          # 配置文件
│   └── hina.ts      # Hina 跟踪器配置
├── constant/        # 常量定义
│   ├── eventEnum.ts # 事件类型枚举
│   └── trackType.ts # 跟踪器类型定义
├── core/           # 核心跟踪器实现
│   ├── BaseTracker.ts      # 基础跟踪器类
│   ├── ExposureTracker.ts  # 曝光跟踪器
│   ├── HinaCore.ts         # Hina Web 跟踪器
│   ├── HinaUniCore.ts      # Hina 小程序跟踪器
│   └── TrackerFactory.ts   # 跟踪器工厂
├── utils/          # 工具函数
│   └── loadScript.ts       # 脚本加载工具
├── index.ts        # 入口文件
└── tracker.ts      # 主跟踪器类

许可证

MIT

更新日志

v0.0.1

  • 初始版本发布
  • 支持 Hina 和 HinaUni 跟踪器
  • 支持元素曝光监听
  • 完整的 TypeScript 类型定义