Next.js 的 App Router 中实现 Google Adsense

31 min read

要在 Next.js 的 App Router 中实现 Google Adsense,可以按照以下步骤进行操作:

  1. 访问 Google Adsense 页面并添加您的网页
    首先,前往 Google Adsense 页面并添加您的网页。添加完成后,您会看到 Adsense 代码,其中包含您的 Adsense ID。

  2. 创建 Google Adsense 组件
    在您的 Next.js 应用中创建一个 GoogleAdsense.tsx 组件,如下所示:

    import Script from "next/script";
    
    type Props = {
      pId: string;
    };
    
    const GoogleAdsense: React.FC<Props> = ({ pId }) => {
      if (process.env.NODE_ENV !== "production") {
        return null;
      }
      return (
        <Script
          async
          src={`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-${pId}`}
          crossOrigin="anonymous"
          strategy="afterInteractive"
        />
      );
    };
    
    export default GoogleAdsense;
    

    注意:只有在生产环境中才会加载 Adsense 脚本。

  3. 修改 layout.tsx
    在您的项目中修改 layout.tsx 文件,将 GoogleAdsense 组件添加到根布局中,如下所示:

    import type { Metadata } from "next";
    import { Inter } from "next/font/google";
    import GoogleAdsense from "../components/GoogleAdsense";
    import "./globals.css";
    
    const inter = Inter({ subsets: ["latin"] });
    
    export const metadata: Metadata = {
      title: "Create Next App",
      description: "Generated by create next app",
    };
    
    export default function RootLayout({
      children,
    }: {
      children: React.ReactNode;
    }) {
      return (
        <html lang="en">
          <body className={inter.className}>{children}</body>
          <GoogleAdsense pId="您的Adsense ID" />
        </html>
      );
    }
    
  4. 确保正确引入外部 JS 文件
    在 App Router 中,您需要使用 next/script 来引入外部 JS 文件,而不是直接在 <head> 中插入 <script> 标签。

  5. 忽略控制台警告
    实现 Google Adsense 后,您可能会在 Chrome 开发者工具的控制台中看到警告消息。这些警告是可以忽略的,因为 Google 可以检测到您的 Next.js 应用中的脚本。