挺久没用 Google 分析对它的操作流程都有点陌生了,这里记录一下在 GA 新建站点和添加统计脚本的过程。

新建站点并拿到统计 ID。

  1. 打开:https://analytics.google.com/
  2. 我已经有账号了,所以直接 管理 -> 创建-> 创建媒体资源,一路点下去就能找到统计代码了
  3. 具体操作流程可以看文档:https://support.google.com/analytics/answer/9304153?hl=zh-Hans

最终拿到一串统计代码:

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-0xxxxxxxx"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-0xxxxxxxx');
</script>

其中 G-0xxxxxxxx 这一串就是该网站的统计 ID,记录下来后面要用。

首先确保安装了 @next/third-parties 这个包

npm i @next/third-parties

项目结构如下:

➜ tree ./src -L 2
./src
├── app
│   ├── favicon.ico
│   ├── globals.css
│   ├── layout.tsx
│   ├── modules
│   └── page.tsx
├── components
│   └── ui
└── lib
    └── utils.ts

如果是每个页面都需要添加统计,则修改 src/app/layout.tsx ,将之前记下来的 gaId 填进去

import { GoogleAnalytics } from '@next/third-parties/google'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
      <GoogleAnalytics gaId="G-0xxxxxxxx" />
    </html>
  )
}

GoogleAnalytics 组件放到上面示例的位置,组件内会处理好资源引入的位置和顺序。

应用发布好后,先自己访问一下,这样 GA 就能统计到数据了

参考教程:

扩展阅读:

Next.js 的性能优化之衡量指标