how to add gtag.js to react.js/next.js index.js?
我很抱歉这个菜鸟问题,我刚开始使用 next.js 模板表单 https://github.com/zeit/next.js/tree/canary/examples/hello-world/pages
通常我只会将 gtag.js 添加到 index.html,但对于这个 next.js,只有 index.js。问题是我怎么能包括这个?我曾尝试将 gtag 作为组件并尝试导入它并包含脚本,因为它位于 index.js 的渲染函数中,但到目前为止它不起作用!请帮帮我!
Gtag:
1 2 3 4 5 6 7 8 | <script async src="https://www.googletagmanager.com/gtag/js? id=GA_TRACKING_ID"> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'GA_TRACKING_ID'); |
index.js:
1 2 3 4 | import Link from 'next/link' export default () => ( Hello World. <Link href='/about'>About</Link> ) |
您可以像这样将 gtag func 添加为 lib:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | export const GA_TRACKING_ID = '<YOUR_GA_TRACKING_ID>' // https://developers.google.com/analytics/devguides/collection/gtagjs/pages export const pageview = url => { window.gtag('config', GA_TRACKING_ID, { page_location: url }) } // https://developers.google.com/analytics/devguides/collection/gtagjs/events export const event = ({ action, category, label, value }) => { window.gtag('event', action, { event_category: category, event_label: label, value: value }) } |
关于如何在 NextJS 中添加谷歌分析的完整示例,
你可以看这里