//GoogleAnalytics.tsx
"use client";
import Script from "next/script";
const GoogleAnalytics = ({ GA_TRACKING_ID }: { GA_TRACKING_ID: string }) => {
return (
<>
<Script
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', ${GA_TRACKING_ID});
`}
</Script>
</>
);
};
export default GoogleAnalytics;
//layout.tsx
import GoogleAnalytics from "@/components/molecules/GoogleAnalytics";
import { ReactNode } from "react";
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<GoogleAnalytics GA_TRACKING_ID={process.env.GA_TRACKING_ID} />
<body>
{children}
</body>
</html>
);
}
With this code, the script tags are properly filled with my ID G-XXXXXXX.
但是,加载页面时,我在浏览器控制台中收到“G 未定义”错误。
VM689:6 Uncaught ReferenceError: G is not defined
at <anonymous>:6:26
at loadScript (webpack-internal:///(:3000/app-client)/./node_modules/.pnpm/[email protected] /cdn-cgi/l/email-protection_dpxg4zawgzznnxdt7it3f5d76m/node_modules/next/dist/client/script.js:91:19)
at eval (webpack-internal:///(:3000/app-client)/./node_modules/.pnpm/[email protected] /cdn-cgi/l/email-protection_dpxg4zawgzznnxdt7it3f5d76m/node_modules/next/dist/client/script.js:182:17)
at commitHookEffectListMount (webpack-internal:///(:3000/app-client)/./node_modules/.pnpm/[email protected] /cdn-cgi/l/email-protection_dpxg4zawgzznnxdt7it3f5d76m/node_modules/next/dist/compiled/react-dom/cjs/react-dom.development.js:26416:26)
我已经尝试将 GoogleAnalytics 标签放置在 body 中以及 head.tsx 中。同样的错误。
I found what "G is not defined" stands for.
G is actually the first letter of the tracking ID.
By using template strings here, I didn't realize that the final code was wrong. I am not importing a string here, but literally the tracking ID which is therefore considered a variable.
为了解决这个问题,我简单地添加了引号:
gtag('config', '${GA_TRACKING_ID}');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)