如何在搭配Twin.Macro/Styled Components的NextJS中修改_document.js接入Google Analytics
解决方法
你现有的_document.js只实现了服务端收集styled-components样式的getInitialProps静态方法,教程里的render方法可以直接追加到你的自定义Document类中,两者完全不冲突,合并后的完整代码如下:
import React from 'react' import Document, { Html, Head, Main, NextScript } from 'next/document' import { ServerStyleSheet } from 'styled-components' export default 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() } } render() { return ( <Html> <Head> {/* Global Site Tag (gtag.js) - Google Analytics */} <script async src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}`} /> <script dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS}', { page_path: window.location.pathname, }); `, }} /> </Head> <body> <Main /> <NextScript /> </body> </Html> ) } }
注意事项
- 确保你的项目环境变量中已经配置了
NEXT_PUBLIC_GOOGLE_ANALYTICS,值为你的Google Analytics ID - 原有styled-components的服务端渲染逻辑和Twin.macro的配置不会受新增代码影响
内容的提问来源于stack exchange,提问作者antonwilhelm
相关产品推荐
相关产品推荐

