在 Next.js 中 添加 Google Analytics
挺久没用 Google 分析对它的操作流程都有点陌生了,这里记录一下在 GA 新建站点和添加统计脚本的过程。 新建站点并拿到统计 ID。 打开:https://analytics.google.com/ 我已经有账号了,所以直接 管理 -> 创建-> 创建媒体资源,一路点下去就能找到统计代码了 具体操作流程可以看文档: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 填进去 ...