首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Gatsby项目中加载React GTM模块

如何在Gatsby项目中加载React GTM模块
EN

Stack Overflow用户
提问于 2021-09-03 16:37:51
回答 2查看 197关注 0票数 0

我正在尝试在我的Gatsby项目中使用react-gtm-module,我使用库@loadable/component在我的组件中加载了这个模块。因此,当我运行gatsby develop时,我得到错误TagManager.initialize is not a function

代码如下:

代码语言:javascript
复制
import loadable from '@loadable/component';

const TagManager = loadable(() => import('react-gtm-module'));

export const setupGtm = () => {
  if (typeof window !== 'undefined') {
    TagManager.initialize({
      gtmId: 'GTM-ID',
    });
  }
};

我真的很想使用react-gtm-module,因为我已经预先配置了几个代码,有人知道如何使用no gatsby吗?

谢谢!!

EN

回答 2

Stack Overflow用户

发布于 2021-09-03 16:47:22

为了让它正常运行,你必须在你的Gatsby项目中安装名为Google Tagmanager的gatsby插件,你可以这样做。通过运行

npm install gatsby-plugin-google-tagmanager

完成后,您必须在您的gatsby-config.jsgatsby-config.ts文件中设置插件。

有关更多信息,请查看来自盖茨比的this doc

票数 0
EN

Stack Overflow用户

发布于 2021-09-06 04:57:11

不要使用基于React的依赖关系。使用原生Gatsby插件很容易做到这一点,因为它们会自动将脚本插入所需的位置。我建议从该代码片段开始,使用gatsby-plugin-google-tagmanager

代码语言:javascript
复制
// In your gatsby-config.js
plugins: [
  {
    resolve: "gatsby-plugin-google-tagmanager",
    options: {
      id: "YOUR_GOOGLE_TAGMANAGER_ID",

      // Include GTM in development.
      //
      // Defaults to false meaning GTM will only be loaded in production.
      includeInDevelopment: false,

      // datalayer to be set before GTM is loaded
      // should be an object or a function that is executed in the browser
      //
      // Defaults to null
      defaultDataLayer: { platform: "gatsby" },

      // Specify optional GTM environment details.
      gtmAuth: "YOUR_GOOGLE_TAGMANAGER_ENVIRONMENT_AUTH_STRING",
      gtmPreview: "YOUR_GOOGLE_TAGMANAGER_ENVIRONMENT_PREVIEW_NAME",
      dataLayerName: "YOUR_DATA_LAYER_NAME",

      // Name of the event that is triggered
      // on every Gatsby route change.
      //
      // Defaults to gatsby-route-change
      routeChangeEventName: "YOUR_ROUTE_CHANGE_EVENT_NAME",
      // Defaults to false
      enableWebVitalsTracking: true,
    },
  },
]

您可以省略不会使用的选项。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69048184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档