是否可以在 gatsby-node.js 中设置 Analytics ID?
Is it possible to set the Analytics ID in gatsby-node.js?
我正在使用 Gatsby 创建静态页面。内容来自带有 rest-API.
的 CMS
现在我想添加Google-Analyitcs,并将trackingId保存在CMS中。
但是当我使用 gatsby-plugin-google-analytics
时,我必须在 gatsby-config.js
.
中设置 trackingId
有什么方法可以获取 gatsby-node.js
中的数据,然后 set/change 插件的 trackingId?
非常感谢您的帮助。
不,你不能。
最后,gatsby-plugin-google-analytics
或任何类似的插件所做的是 customize the html.js
to add a script with the ID in it. This is created as a boilerplate/template for the content coming from your data sources (in your gatsby-node.js
) while your site is being built, as you can see in the docs:
Gatsby gives plugins and site builders many APIs for building your
site. Code in the file gatsby-node.js
is run once in the process of
building your site. You can use its APIs to create pages dynamically,
add data into GraphQL, or respond to events during the build
lifecycle.
Every Gatsby Node API gets passed a set of helper functions. These let
you access several methods like reporting, or perform actions like
creating new pages.
但是,您可以根据您的 CMS 内容通过 React Helmet
手动设置跟踪 ID,这样实现起来会更简单。在您的 createPage
函数中,您可以执行以下操作:
createPage({
path: `/somePath/${node.id}`,
component: yourComponent,
context: {
trackingId: node.trackingId,
},
})
trackingId
代表您的分析跟踪 ID,将在您的前端视图中的 props.pageContext.trackingId
下提供。
我正在使用 Gatsby 创建静态页面。内容来自带有 rest-API.
的 CMS现在我想添加Google-Analyitcs,并将trackingId保存在CMS中。
但是当我使用 gatsby-plugin-google-analytics
时,我必须在 gatsby-config.js
.
有什么方法可以获取 gatsby-node.js
中的数据,然后 set/change 插件的 trackingId?
非常感谢您的帮助。
不,你不能。
最后,gatsby-plugin-google-analytics
或任何类似的插件所做的是 customize the html.js
to add a script with the ID in it. This is created as a boilerplate/template for the content coming from your data sources (in your gatsby-node.js
) while your site is being built, as you can see in the docs:
Gatsby gives plugins and site builders many APIs for building your site. Code in the file
gatsby-node.js
is run once in the process of building your site. You can use its APIs to create pages dynamically, add data into GraphQL, or respond to events during the build lifecycle.Every Gatsby Node API gets passed a set of helper functions. These let you access several methods like reporting, or perform actions like creating new pages.
但是,您可以根据您的 CMS 内容通过 React Helmet
手动设置跟踪 ID,这样实现起来会更简单。在您的 createPage
函数中,您可以执行以下操作:
createPage({
path: `/somePath/${node.id}`,
component: yourComponent,
context: {
trackingId: node.trackingId,
},
})
trackingId
代表您的分析跟踪 ID,将在您的前端视图中的 props.pageContext.trackingId
下提供。