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

如何在Docusaurus自定义按钮中获取GitHub仓库Star数(无需iframe)

解决方案:在自定义按钮中添加GitHub仓库Star数(React/Docusaurus)

你之前用的API参数完全不对,GitHub没有带type=star&count=true这类参数的端点,正确做法是调用仓库详情API来获取Star数。

正确的GitHub API用法

获取仓库Star数的核心API是:

GET https://api.github.com/repos/{owner}/{repo}

返回的JSON数据里,stargazers_count字段就是你要的Star总数。

注意:未认证的API请求每小时限制60次,认证请求(带GitHub PAT)每小时5000次。对于静态站点来说,构建时预获取数据是最优解,既避免客户端请求限制,又能保证页面加载速度。

Docusaurus/React场景的两种实现方式

方式一:构建时预获取(推荐)

在Docusaurus中,可以通过自定义组件结合构建时数据获取来实现:

  1. 创建自定义React组件GitHubStarButton.js:
import React from 'react';

export default function GitHubStarButton({ owner, repo, starCount }) {
  return (
    <button className="custom-star-btn">
      <span className="star-icon">⭐</span>
      <span>{starCount || '0'}</span>
    </button>
  );
}

// 构建时获取Star数的逻辑(适配Docusaurus静态生成)
export async function getStaticProps() {
  const res = await fetch(`https://api.github.com/repos/{owner}/{repo}`);
  const data = await res.json();
  return {
    props: {
      starCount: data.stargazers_count,
    },
    // 可选:每24小时重新构建更新数据
    revalidate: 86400,
  };
}
  1. 在MDX页面或其他组件中引入,样式完全自定义:
.custom-star-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
}

.custom-star-btn:hover {
  background: #f6f8fa;
  border-color: #ccc;
}

.star-icon {
  color: #ffd700;
}

方式二:客户端动态获取

如果需要实时更新Star数(比如不想频繁触发站点构建),可以在客户端发起请求:

import React, { useState, useEffect } from 'react';

export default function GitHubStarButton({ owner, repo }) {
  const [starCount, setStarCount] = useState(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    // 缓存Star数1小时,减少API请求
    const cachedCount = localStorage.getItem(`github-star-${owner}-${repo}`);
    const cachedTime = localStorage.getItem(`github-star-time-${owner}-${repo}`);
    if (cachedCount && cachedTime && Date.now() - parseInt(cachedTime) < 3600000) {
      setStarCount(cachedCount);
      return;
    }

    fetch(`https://api.github.com/repos/${owner}/${repo}`)
      .then(res => res.json())
      .then(data => {
        setStarCount(data.stargazers_count);
        localStorage.setItem(`github-star-${owner}-${repo}`, data.stargazers_count);
        localStorage.setItem(`github-star-time-${owner}-${repo}`, Date.now().toString());
      })
      .catch(() => setError(true));
  }, [owner, repo]);

  if (error) return <button className="custom-star-btn">⭐ Error</button>;
  return (
    <button className="custom-star-btn">
      <span className="star-icon">⭐</span>
      <span>{starCount || 'Loading...'}</span>
    </button>
  );
}

关键注意事项

  • 处理请求失败:一定要加错误捕获,避免页面崩溃
  • 认证问题:如果站点访问量较大,或需要访问私有仓库,建议在构建时使用GitHub PAT(存在环境变量中,绝不能暴露到前端)
  • 样式自定义:完全可以根据站点设计调整按钮的颜色、尺寸、hover效果,不受iframe按钮的限制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 18:40:32