//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;
Run Code Online (Sandbox Code Playgroud)
//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> …Run Code Online (Sandbox Code Playgroud) 如何在 Vite 构建中保留初始脚本标签顺序?
在我的index.html head 标签中:
<script src="js/initMap.js" type="module"></script>
<script defer src="https://maps.googleapis.com/maps/api/"></script>
Run Code Online (Sandbox Code Playgroud)
在我的构建中:
<script defer src="https://maps.googleapis.com/maps/api/"></script>
<script src="js/initMap.js" type="module"></script>
Run Code Online (Sandbox Code Playgroud)