如何在 gatsby js 文件中插入 google 分析标签?

How to insert a google anylitics tag inside of a gatsby js file?

正在尝试弄清楚如何将 google-analytics 标记放在 Gatsby 的 js 文件的一侧。

有一个 gatsby-plugin-analytics plugin ,但是那里显示的示例没有给出放置 google 分析标签的想法。

最简单和可维护的方法是使用插件。 gatsby-plugin-google-analytics 应该适合你:

// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-google-analytics`,
      options: {
        // You can add multiple tracking ids and a pageview event will be fired for all of them.
        trackingIds: [
          "GA-TRACKING_ID", // Google Analytics / GA
        ],
        // This object gets passed directly to the gtag config command
        // This config will be shared across all trackingIds
        gtagConfig: {
          optimize_id: "OPT_CONTAINER_ID",
          anonymize_ip: true,
          cookie_expires: 0,
        },
        // This object is used for configuration specific to this plugin
        pluginConfig: {
          // Puts tracking script in the head instead of the body
          head: false,
          // Setting this parameter is also optional
          respectDNT: true,
          // Avoids sending pageview hits from custom paths
          exclude: ["/preview/**", "/do-not-track/me/too/"],
        },
      },
    },
  ],
}

注意:您可以omit/remove可选参数,您只需将GA-TRACKING_ID替换为您的标识符即可。

他们最近更改了一些 API 参数,使您的插件(和其他一些)无法使用。提供的是Gatsby在一些教程部分推荐的。

或者,根据您的 Gatsby 和插件版本,以下插件也可能适用于您:

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-google-gtag`,
      options: {
        trackingIds: [
          "GA-TRACKING_ID", // Google Analytics / GA
        ],
      },
    },
  ],
}