You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在无layouts/components文件夹的Astro Starlight主题中添加Google Analytics

Astro Starlight主题集成Google Analytics指南

针对最新版Starlight无传统layouts/components文件夹的情况,提供两种可行方案:

方案1:内置配置集成(GA4优先)

如果使用GA4(ID格式G-XXXXXXX),直接修改项目根目录的astro.config.mjs:

import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
  integrations: [
    starlight({
      title: '你的站点标题',
      analytics: {
        provider: 'google',
        id: 'G-XXXXXXX', // 替换为你的GA4 ID
      },
    }),
  ],
});

注意:该方式不支持旧版UA格式(UA-XXXXX-Y),需用下方自定义方案。

方案2:自定义Head组件注入UA脚本

通过替换Starlight默认Head组件来注入跟踪代码:

  1. 手动创建src/components文件夹,新建Head.astro文件:
---
// 引入默认Head组件,保留原有页面头部功能
import DefaultHead from '@astrojs/starlight/components/Head.astro';
---

<DefaultHead />

<!-- Google Analytics UA跟踪代码 -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXX-Y"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-XXXXX-Y'); // 替换为你的UA ID
</script>
  1. 更新astro.config.mjs,指定使用自定义Head组件:
import { defineConfig } from 'astro/config';
import starlight from '@astrojs/starlight';

export default defineConfig({
  integrations: [
    starlight({
      title: '你的站点标题',
      components: {
        Head: './src/components/Head.astro',
      },
    }),
  ],
});

完成后重启开发服务器,跟踪代码会自动插入所有页面的<head>中。

内容的提问来源于stack exchange,提问作者Ricardo Rosero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 18:34:51