第三方库
**@next/third-parties**是一个库,它提供了一系列组件和工具,以提高在 Next.js 应用程序中加载流行第三方库的性能和开发者体验。
所有由@next/third-parties提供的第三方集成都已针对性能和易用性进行了优化。
开始
要开始使用,请安装@next/third-parties库:
npm install @next/third-parties@latest next@latest
@next/third-parties目前是一个** 实验性** 库,正在积极开发中。我们建议在安装时使用latest或canary标志,同时我们正在努力添加更多第三方集成。
Google 第三方
所有 Google 支持的第三方库都可从@next/third-parties/google导入。
Google Tag Manager
GoogleTagManager组件可用于将Google Tag Manager容器实例化到您的页面。默认情况下,它会在页面水合后获取原始内联脚本。
要为所有路由加载 Google Tag Manager, 请将组件直接包含在根布局中,并传入您的 GTM 容器 ID:
import { GoogleTagManager } from "@next/third-parties/google";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<GoogleTagManager gtmId="GTM-XYZ" />
<body>{children}</body>
</html>
);
}
import { GoogleTagManager } from "@next/third-parties/google";
export default function RootLayout({ children }) {
return (
<html lang="en">
<GoogleTagManager gtmId="GTM-XYZ" />
<body>{children}</body>
</html>
);
}
要为单个路由加载 Google Tag Manager, 请在页面文件中包含该组件:
import { GoogleTagManager } from "@next/third-parties/google";
export default function Page() {
return <GoogleTagManager gtmId="GTM-XYZ" />;
}
发送时间
sendGTMEvent函数可用于通过使用dataLayer对象发送事件来跟踪页面上的用户交互。要使此函数正常工作,必须在父布局、页面或组件中,或直接在同一文件中包含 <GoogleTagManager />组件。
"use client";
import { sendGTMEvent } from "@next/third-parties/google";
export function EventButton() {
return (
<div>
<button
onClick={() => sendGTMEvent("event", "buttonClicked", { value: "xyz" })}
>
Send Event
</button>
</div>
);
}
请参阅 Tag Manager开发者文档以了解可以传递给该函数的不同变量和事件。