我在 next.js 中使用样式化组件,所以我的样式需要在服务器端呈现,因此如何将谷歌分析添加到我的网站?
我检查了 next.js 谷歌分析示例,但正如我所说,我的 _document 文件因使用样式化组件而不同。
// _document.js
import React from 'react'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () => originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
export default MyDocument
原文由 0xsh 发布,翻译遵循 CC BY-SA 4.0 许可协议
Next.js 因为 v11 建议 使用他们的
<Script>
标签,添加它的正确位置是App
组件。pages/_app.jsx
你可以看到这个解决方案在 nestjs-starter 中工作,我也在其中设置来自 env var 的标签。
这也会自动记录导航的综合浏览量。如果这不适合您,可以使用手动发送页面浏览事件的 官方示例 或使用 React Router 执行此操作的 线程。
要发送自定义事件,您可以使用
window.gtag
。它甚至支持 TypeScript:@types/gtag.js
对于 v10 和更低版本,请根据 Google 指南 使用常规
<script>
标签。