









Older iterations of this website used a third party JavaScript widget to show the number of GitHub Stars the project currently had. You can see it in action on the versioned docs for 0.7.1 (scroll to the bottom).
This was in fact the only <script> tag on the entire 11ty.dev web site and it was from a third party. Naturally, it needed to be annihilated.
Let’s change up our architecture to ruthlessly eliminate this client-side JavaScript.
Read more at the GitHub API documentation.
This is a bit different from our client-side implementation because this data is only updated as often as your build runs. This is implemented using a global JavaScript data file at _data/github.js.
npm install node-fetchnode-fetch_data/github.js
import fetch from "node-fetch";
export default async function () {
console.log("Fetching new github stargazers count…");
// GitHub API: https://developer.github.com/v3/repos/#get
let res = await fetch("https://api.github.com/repos/11ty/eleventy");
let json = await res.json();
// prune the data to return only what we want
return {
stargazers: json.stargazers_count,
};
};
const fetch = require("node-fetch");
module.exports = async function () {
console.log("Fetching new github stargazers count…");
// GitHub API: https://developer.github.com/v3/repos/#get
let res = await fetch("https://api.github.com/repos/11ty/eleventy");
let json = await res.json();
// prune the data to return only what we want
return {
stargazers: json.stargazers_count,
};
};
Now in your templates you can output the stargazers count with:
Syntax Liquid, Nunjucks
{{ github.stargazers }} GitHub Stars
which outputs
1515 GitHub Stars
Bonus: I created a humanReadableNum filter) using the human-readable-numbers package to format the number.
You can look in the footer of this page to see examples of this in use on this very web site. I used it for:
These all use the recommended caching mechanism described in the next section.
If you want to update these counts automatically every day, read Quick Tip #008—Trigger a Netlify Build Every Day with IFTTT.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。