立即迁移到 Netlify

Netlify 宣布 Gatsby Cloud 的下一次迭代。 了解更多

联系我们注册
社区插件
在 GitHub 上查看插件

gatsby-plugin-segment-js

一个轻量级且功能丰富的 Gatsby 插件,可轻松将 Segment JS 代码段 添加到您的站点。

我们需要您的帮助! 🙏🏽

我们正在寻找该仓库的活跃贡献者!如果您有兴趣,只需打开您自己的 issue 或 PR 并注明您想提供帮助。查看我们开放的 issue 和 PR。我们还需要加强测试。贡献者可以

  • 通过将新版本发布到 NPM 来管理版本和部署
  • 通过合并拉取请求来决定哪些功能被发布
  • 通过评论和管理拉取请求及 issue 来监督社区

⚜️ 成为一名活跃的贡献者对社区和您的工程简历都大有裨益。⚜️

功能

功能丰富

  • 使用多个写入密钥(一个用于生产环境,另一个可选的用于开发环境)
  • 禁用页面视图跟踪(以防您以后手动添加)
  • 将使用默认的 Segment 代码段(目前是 v4.15.3),或者您可以提供自己的自定义代码段

安装

  • NPM: $ npm install --save gatsby-plugin-segment-js
  • YARN: $ yarn add gatsby-plugin-segment-js

如何使用

设置

在您的 gatsby-config.js 文件中

plugins: [
  {
    resolve: `gatsby-plugin-segment-js`,
    options: {
      // your segment write key for your production environment
      // when process.env.NODE_ENV === 'production'
      // required; non-empty string
      prodKey: 'SEGMENT_PRODUCTION_WRITE_KEY',

      // if you have a development env for your segment account, paste that key here
      // when process.env.NODE_ENV === 'development'
      // optional; non-empty string
      devKey: 'SEGMENT_DEV_WRITE_KEY',

      // Boolean indicating if you want this plugin to perform any automated analytics.page() calls
      // at all, or not.
      // If set to false, see below on how to track pageviews manually.
      // 
      // This plugin will attempt to intelligently prevent duplicate page() calls.
      // 
      // Default: true
      trackPage: true,

      // Boolean indicating if you want this plugin to perform a page() call immediately once the snippet
      // is loaded.
      // 
      // You might want to disable this if you *only* want page() calls to occur upon Client-side routing
      // updates. See `trackPageOnRouteUpdate` option.
      // 
      // This plugin will still attempt to intelligently prevent duplicate page() calls.
      // 
      // Default: true
      trackPageImmediately: true,

      // Boolean indicating whether to ignore `page` calls by this plugin before we call `analytics.load`
      // and/or the `ready` event has been emitted by `analytics`.
      // 
      // Useful in some cases to prevent issues "queuing" `page` events before Segment is fully loaded.
      trackPageOnlyIfReady: false,

      // Boolean indicating whether to perform any page() calls during Client-side routing updates.
      // 
      // You might want to disable `trackPageImmediately` if you *only* want page() calls to occur upon
      // Client-side routing updates.
      // 
      // This plugin will still attempt to intelligently prevent duplicate page() calls.
      // 
      // Default: true
      trackPageOnRouteUpdate: true,

      // Number indicating what delay (in ms) should be used when calling analytics.page() in response
      // to a Gatsby `onRouteUpdate` event. This can help to ensure that the segment route tracking is 
      // in sync with the actual Gatsby route. Otherwise you can end up in a state where the Segment
      // page tracking reports the previous page on route change.
      // 
      // See https://gatsbyjs.com.cn/docs/reference/config-files/gatsby-browser/ for more information.
      // 
      // Default: 50
      trackPageOnRouteUpdateDelay: 50,

      // Boolean indicating whether or not to add the document.title as the first argument to
      // the analytics.page() calls. Segment uses some sane defaults, but some users of this plugin
      // have wanted to do this in the past.
      // 
      // E.g `analytics.page(document.title)`
      // 
      // Default: false
      trackPageWithTitle: false,
      
      // Boolean indicating whether to call analytics.load() immediately, or to delay it by a specified
      // number of ms. Can be useful if you want to wait a specifc amount of time before calling
      // analytics.load() and kicking off the activity that occurs with that call.
      // 
      // Default: false
      delayLoad: false,

      // Number indicating (in ms) how long to wait for before analytics.load() will be called if
      // the `delayLoad` option is set to `true`.
      // 
      // Default: 1000
      delayLoadDelay: 1000,

      // Boolean indicating whether to delay calling analytics.load() until either:
      // 1) The User interacts with the page by scrolling
      // OR
      // 2) The User triggers a Gatsby route change.
      // 
      // The `delayLoad` option can be used in addition to this option.
      // 
      // NOTE: 
      // The route change will only be triggered if you leverage client-side routing (ie, Gatsby <Link>)
      // So if you leverage server-side routing with this feature, only a User scroll will trigger
      // the `load` call. This is because client-side routing does not do
      // a full page refresh, but server-side routing does. Therfore server-side routing will never
      // appear to have been triggered by a User interaction.
      // 
      // This is an advanced feature most often used to try to help improve your website's TTI (for SEO, UX, etc).
      // 
      // See here for more context:
      // Client-side routing and browser code: https://gatsbyjs.com.cn/docs/reference/config-files/gatsby-browser/
      // GIF: https://github.com/benjaminhoffman/gatsby-plugin-segment-js/pull/19#issuecomment-559569483
      // TTI: https://github.com/GoogleChrome/lighthouse/blob/master/docs/scoring.md#performance
      // Problem/solution: https://marketingexamples.com/seo/performance
      // 
      // Default: false
      delayLoadUntilActivity: false,

      // Number indicating (in ms) any additional delay to wait before calling analytics.load()
      // after User "activity" has occurred in conjunction with the `delayLoadUntilActivity` option.
      // 
      // Default: 0
      delayLoadUntilActivityAdditionalDelay: 0,

      // Whether to completely skip calling `analytics.load({writeKey})`.
      // ADVANCED FEATURE: only use if you are calling `analytics.load({writeKey})` manually
      // elsewhere in your code or are using a library
      // like: https://github.com/segmentio/consent-manager that will call it for you.
      // Useful for only loading the tracking script once a user has opted in to being tracked, for example.
      // 
      // Default: false
      manualLoad: false,

      // If you need to proxy events through a custom endpoint,
      // add a `host` property (defaults to https://cdn.segment.io)
      // Segment docs:
      //   - https://segment.com/docs/connections/sources/custom-domains
      //   - https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#proxy
      // 
      // Default: 'https://cdn.segment.io'
      host: 'https://override-segment-endpoint',

      // This package will use a default version of Segment's code snippet, but
      // if you'd like to include your own you can do so here. This is useful if
      // the version this package uses is different than the one you'd like to
      // use...or you need to do something custom.
      // While you should NOT use a back-ticked template string here, the string
      // will be evaluated as template literal with the following variables
      // available to it:
      //    - `writeKey`: The appropriate value from the `prodKey` and `devKey`
      //      options, based on the `NODE_ENV`
      //    - any of the other options passed here
      // 
      // NOTES: 
      // - If you provide a custom snippet, an immediate call to
      //   `analytics.load()` and/or `analytics.page()` will not be added by
      //   this plugin. You can - of course - add them yourself to your snippet.
      // - If your custom snippet does not include a call to `analytics.load()`
      //   then you must either:
      //   1. Manually load it and set the `manualLoad` option here to `true`
      //   2. Use the `delayLoad` option here
      customSnippet: '!function(){var analytics=window.analytics||[];...;analytics.load("${writeKey}");analytics.page();}}();'
    }
  }
];

加载

使用此插件的典型 Segment 设置将在页面中添加一个初始的 Segment “代码段”。一旦该代码段存在,就需要通过调用 analytics.load(<your segment key here>) 来“加载”它,然后才能实际发送任何事件到 Segment。此 load 调用会引发一系列 XHR 请求,有些人似乎非常担心这些请求不会延迟发生——通常是为了 SEO 分数,尽管我不清楚 Segment 处理 load 调用是否会影响 TTI 等。无论如何,如果您希望此插件延迟调用 load,您有 2 种选择:1. delayLoad:这将导致在调用 load 之前有一个直接的延迟。与 delayLoadDelay 结合使用以调整延迟量。2. delayLoadUntilActivity:这将等待,直到用户触发“滚动”事件**或**用户触发路由更改,然后才调用 load。此选项将优先于 delayLoad 选项。

跟踪事件

如果您想跟踪事件,只需像平常一样在您的 React 组件中调用 Segment —(window.analytics.track('Event Name', {...}) — 然后您应该会在 Segment 调试器中看到这些事件!例如,如果您想跟踪点击事件,可能会像这样

class IndexPage extends React.Component {
    ...
    _handleClick() {
        window.analytics.track("Track Event Fired", {
            userId: user.id,
            gender: 'male',
            age: 33,
        });
    }
    render() {
        return (
            <p>
                <Link onClick={this._handleClick} to="/">
                    Click here
                </Link>{" "}
                to see a track event
            </p>
        );
    }
}

跟踪页面视图

如果您想自动跟踪页面视图,请在您的 gatsby-config.js 文件中将 trackPage 设置为(或保留为)true。我们所说的“自动”是指我们将智能地决定如何或何时为您调用 window.analytics.page()

这包括识别最后一个 page 调用是在用户位于与上一个 page 调用相同的 location.pathname 时完成的。如果它们看起来相同,我们将跳过重复的调用。

如果您愿意,此插件还可以利用 Gatsby 的 gatsby-browser.js 文件中的 onRouteUpdate API(链接)。这是通过在 gatsby-browser.js 文件中将 trackPageOnRouteUpdate 设置为(或保留为)true 来实现的。如果启用了此选项,每次调用 onRouteUpdate 处理程序时,我们都会进行一次 page 调用。这包括初始路由和任何路由更改。

如果您只想使用此插件来注入和加载 Segment,而不进行任何 page 调用,这也是可以做到的。只需将 trackPage: false 设置为 false。但然后您将不得不在您的 gatsby-browser.js 文件中自己调用 page 调用,如下所示

// gatsby-browser.js
exports.onRouteUpdate = () => {
  window.analytics && window.analytics.page();
};
©2025Gatsby, Inc.