Fathom Client 开源项目教程
项目介绍
Fathom Client 是一个用于与 Fathom Analytics 服务进行交互的 JavaScript 客户端库。Fathom Analytics 是一个注重隐私的网站分析工具,旨在提供简单、快速且不跟踪用户的访问数据。Fathom Client 使得开发者能够轻松地将 Fathom Analytics 集成到他们的项目中,无论是传统的网页应用还是现代的单页应用(SPA)。
项目快速启动
安装
首先,你需要在你的项目中安装 Fathom Client。你可以使用 npm 或 yarn 进行安装:
npm install @fathom-client/fathom-client
或者
yarn add @fathom-client/fathom-client
基本使用
在你的项目中引入并初始化 Fathom Client:
import * as Fathom from '@fathom-client/fathom-client';
// 初始化 Fathom
Fathom.load('YOUR_SITE_ID', {
includedDomains: ['example.com'],
});
// 可选:跟踪页面加载
document.addEventListener('DOMContentLoaded', () => {
Fathom.trackPageview();
});
应用案例和最佳实践
单页应用(SPA)集成
对于单页应用,你需要在每次路由变化时手动调用 trackPageview
方法:
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import * as Fathom from '@fathom-client/fathom-client';
const App = () => {
const location = useLocation();
useEffect(() => {
Fathom.trackPageview();
}, [location]);
return (
<div>
{/* 你的应用内容 */}
</div>
);
};
export default App;
高级配置
Fathom Client 提供了一些高级配置选项,例如排除特定域名或自定义事件跟踪:
Fathom.load('YOUR_SITE_ID', {
includedDomains: ['example.com'],
excludedDomains: ['test.example.com'],
});
// 自定义事件跟踪
Fathom.trackEvent('example-event', {
goal: 'Example Goal',
value: 100,
});
典型生态项目
Next.js 集成
Fathom Client 与 Next.js 集成非常简单。以下是一个基本的集成示例:
// pages/_app.js
import { useEffect } from 'react';
import * as Fathom from '@fathom-client/fathom-client';
const MyApp = ({ Component, pageProps }) => {
useEffect(() => {
Fathom.load('YOUR_SITE_ID', {
includedDomains: ['example.com'],
});
}, []);
return <Component {...pageProps} />;
};
export default MyApp;
Gatsby 集成
对于 Gatsby 项目,你可以在 gatsby-browser.js
中进行集成:
// gatsby-browser.js
import * as Fathom from '@fathom-client/fathom-client';
export const onRouteUpdate = () => {
Fathom.trackPageview();
};
export const onClientEntry = () => {
Fathom.load('YOUR_SITE_ID', {
includedDomains: ['example.com'],
});
};
通过这些示例,你可以看到 Fathom Client 如何轻松地集成到不同的前端框架中,提供一致的分析体验。